Javascript: textContent based on textLength

Javascript: textContent based on textLength

本文关键字:on textLength based textContent Javascript      更新时间:2023-09-26

大家好(第一张海报,所以还不要开枪打我…):

我正在尝试根据文本长度更改文本区域。

我的代码如下:

<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)中获取所选项目,然后选择文本并将其添加到文本区域(称为注释)。

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

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

尝试使用而不是textContent来编写文本区域的内容。

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

这是您正在讨论的代码片段:

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

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

currentComment.textContent = selectedComment;

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