2017-03-08 70 views
1

我想用TEXTAREA中的****替換某些單詞,但此腳本不起作用。感謝您的幫助替換textarea中的文字

<TEXTAREA style="color:black;" name="Body" id="Body" value="" rows="6" cols="60" maxlength="160"></TEXTAREA><br/> 
<script> 
var input = document.getElementById('Body')[0], 
    output = document.getElementById('Body')[0], 
    badwords = /\b(test|test2|test3)\b/g; 

input.onkeyup = function() { 
    output.innerHTML = this.value.replace(badwords, function (fullmatch, badword) { 
     return '<sub>' + new Array(badword.length + 1).join('*') + '</sub>'; 
    }); 
}; 

input.onkeyup(); 
input.focus(); 
</script> 

回答

0

這裏是一個有效的解決方案,以在評論中解釋:

//remove [0]. getElementById returns an element, not a collection: 
 
var input = document.getElementById('Body'), 
 
    output = document.getElementById('Body'), 
 
    badwords = /\b(test1|test2|test3)\b/g; 
 

 
//addEventListener is the best way to add listeners: 
 
input.addEventListener('keyup', function() { 
 

 
//Change innerHTML to value here: 
 
    output.value = this.value.replace(badwords, function (fullmatch, badword) { 
 

 
//Remove '<sub>...</sub>'. Textareas support text content only. 
 
    return new Array(badword.length + 1).join('*'); 
 
    }); 
 
}); 
 

 
input.focus();
<TEXTAREA style="color:black;" name="Body" id="Body" value="" rows="6" cols="60" maxlength="160"></TEXTAREA><br/>

+0

GREAT!非常感謝你 !!你是最好的:D – Chrys