简体   繁体   English

Javascript:基于textLength的textContent

[英]Javascript: textContent based on textLength

Hi all (first poster so don't shoot me...yet): 大家好(第一张海报,所以不要射击我...):

I'm trying to alter a textarea based on the textlength. 我正在尝试根据文本长度更改文本区域。

My code is as follow: 我的代码如下:

<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>

What I'm trying to do is get the selected item from a option (called commentBank), from this, get the text selected and add it to a textarea (called comment). 我想做的是从一个选项(称为commentBank)中获取选定的项目,从中获取所选的文本并将其添加到textarea(称为comment)中。

The issue at present is that when currentComment.textContent () is equal to 0, it doesn't add the text to the textarea. 当前的问题是,当currentComment.textContent()等于0时,它不会将文本添加到textarea中。 It does output to the log however, doesn't update the textarea to add the text, so the if statement is working. 它确实输出到日志,但是不会更新textarea来添加文本,因此if语句可以正常工作。

Any ideas? 有任何想法吗? Thanks in advanced. 提前致谢。

This is the code snippet you're talking about: 这是您正在谈论的代码片段:

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

The reason it doesn't actually add the comment is because you are setting currentComment.textContent to the string "selectedComment" , not the value . 实际上没有添加注释的原因是因为您将currentComment.textContent设置为字符串 "selectedComment" ,而不是value That's why it prints okay in your log (because you're logging the value). 这就是为什么它在您的日志中可以正常打印的原因(因为您正在记录该值)。 Change that line to: 将该行更改为:

currentComment.textContent = selectedComment;

(Note the absence of the quotation marks, which creates a string with the literal value selectedComment .) (请注意,没有引号会创建一个字符串,其字面值为selectedComment 。)

Try using value instead of textContent , to write the content of a textarea. 尝试使用value而不是textContent来编写文本区域的内容。

I don't know all browsers, but in some of them, textContent is read only. 我不知道所有的浏览器,但是在某些浏览器中,textContent是只读的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM