如何使用 JavaScript 读取 textarea 中的文本?

编程入门 行业动态 更新时间:2024-10-15 16:25:24
本文介绍了如何使用 JavaScript 读取 textarea 中的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

所以我是 JS 的新手,正在尝试了解基础知识.我决定制作一个基本的网页文本编辑器.现在我正试图用 JS 区分单词.这是我拥有的代码,基本上它决定了bob"这个词是否存在.已在 textarea 中输入.

So I am new to JS and am trying to figure out the basics. I decided to make a basic web page text editor. Right now I am trying to differentiate between words with JS. Here is the code I have, basically it determines whether or not the word "bob" has been entered in the textarea.

<script>

function findBob() {
    var inputText = document.getElementById("box").innerHTML;
    if(inputText === "bob") {
        document.getElementById("box").innerHTML = "true";
    } 
    if (inputText !== "bob") {
        document.getElementById("box").innerHTML = "false";
    }
}
</script>

<textarea rows=10; col= 5; id="box">
bob</textarea>

<button onClick="findBob();">FIND BOB</button>

现在,在我单击FIND BOB"按钮后,它会将文本更改为true";这是完美的,但是,如果我向 textarea 添加一些胡言乱语,然后再次单击 FIND BOB,则没有任何反应.如果我对 textarea 做任何事情,该功能将不起作用.即使我重新加载页面,也会退格bob"并重新输入bob"什么都没有发生.

Now, after I click the button saying "FIND BOB", it changes the text to "true" which is perfect, however, if I add some gibberish to the textarea, then click FIND BOB again, nothing happens. If I do anything to the textarea the function will not work. Even if I reload the page, backspace "bob" and retype "bob" nothing happens.

现在我想我已经破坏了一些 JavaScript 语法,或者一些类似的东西,但我无法弄清楚.我做错了什么?

Now I expect that I have broken some JavaScript syntax, or some such thing, but I cannot figure it out. What am I doing wrong?

-EDIT- 我正在使用 ===,而不是其他方法,因为这个 StackOverflow 帖子,找到它 此处.

-EDIT- I am using ===, as opposed to other methods because of this other StackOverflow post, find it here.

推荐答案

textarea 的 innerHTML 代表它的默认值.

The innerHTML of a textarea represents its default value.

使用 JavaScript 更改默认值仅在以下情况下有效:

Changing the default value with JavaScript only has an effect if either:

该值未从默认值更改表单已重置

在 textarea 中输入后,这些都不对.

After you type in the textarea, neither of these is true.

使用 value 属性来更改 当前 值而不是 innerHTML.

Use the value property to alter the current value and not the innerHTML.

这篇关于如何使用 JavaScript 读取 textarea 中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 13:46:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1410460.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   文本   JavaScript   textarea

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!