Javascript:textContent基于textLength

时间:2012-02-15 01:49:51

标签: javascript

大家好(第一张海报所以不要拍我......):

我正在尝试根据textlength更改textarea。

我的代码如下:

<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(称为注释)。

目前的问题是当currentComment.textContent()等于0时,它不会将文本添加到textarea。 它确实输出到日志,但不更新textarea以添加文本,因此if语句正在工作。

有什么想法吗? 谢谢你提前。

2 个答案:

答案 0 :(得分:0)

这是您正在谈论的代码段:

        }else if(currentComment.textLength == 0){
            console.log("Trying to add "+selectedComment);
            currentComment.textContent = "selectedComment";

实际上添加评论的原因是因为您要将currentComment.textContent设置为字符串 "selectedComment",而不是的。这就是为什么它在您的日志中打印正常(因为您正在记录该值)。将该行更改为:

currentComment.textContent = selectedComment;

(注意没有引号,这会创建一个字符值为selectedComment的字符串。)

答案 1 :(得分:0)

尝试使用而不是 textContent 来编写textarea的内容。

我不知道所有浏览器,但在其中一些浏览器中,textContent是只读的。