![](/img/trans.png)
[英]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.