[英]Javascript code to change innerHTML value if textlength > 250
[英]Javascript: textContent based on textLength
大家好(第一張海報,所以不要射擊我...):
我正在嘗試根據文本長度更改文本區域。
我的代碼如下:
<script type="text/javascript">
function addComment(){
var commentBank = document.getElementById("commentBank");
var selectedComment = commentBank.options[commentBank.selectedIndex].text;
var currentComment = document.getElementById("comment");
console.log(currentComment.textLength);
if(currentComment.textContent == "Add comment here" ){
currentComment.textContent = selectedComment;
}else if(currentComment.textLength == 0){
console.log("Trying to add "+selectedComment);
currentComment.textContent = "selectedComment";
}
else{
currentComment.textContent += ". " + selectedComment;
}
}
</script>
我想做的是從一個選項(稱為commentBank)中獲取選定的項目,從中獲取所選的文本並將其添加到textarea(稱為comment)中。
當前的問題是,當currentComment.textContent()等於0時,它不會將文本添加到textarea中。 它確實輸出到日志,但是不會更新textarea來添加文本,因此if語句可以正常工作。
有任何想法嗎? 提前致謝。
這是您正在談論的代碼片段:
}else if(currentComment.textLength == 0){
console.log("Trying to add "+selectedComment);
currentComment.textContent = "selectedComment";
實際上沒有添加注釋的原因是因為您將currentComment.textContent
設置為字符串 "selectedComment"
,而不是value 。 這就是為什么它在您的日志中可以正常打印的原因(因為您正在記錄該值)。 將該行更改為:
currentComment.textContent = selectedComment;
(請注意,沒有引號會創建一個字符串,其字面值為selectedComment
。)
嘗試使用value而不是textContent來編寫文本區域的內容。
我不知道所有的瀏覽器,但是在某些瀏覽器中,textContent是只讀的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.