问题描述
限时送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:关键词]
发布评论