javascript:获取textarea的内容,textContent vs.innerHTML vs.innerText

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16013899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:55:56  来源:igfitidea点击:

javascript: get contents of textarea, textContent vs. innerHTML vs. innerText

javascripttextareagetelementbyid

提问by user1904273

I am having trouble getting the contents of a textarea with js. I feel like I've done this many times before without problems but something is throwing it off or I have a mental block.

我无法使用 js 获取 textarea 的内容。我觉得我以前做过很多次都没有问题,但有什么东西把它扔掉了,或者我有心理障碍。

html

html

<textarea id="productdescript">test copy..asdfd</textarea><button value="Enter" onclick="addProduct()">

js

js

function addProduct() {
var descript = document.getElementById('productdescript').textContent;
alert(descript);
}

Firefox is the only browser I have currently.

Firefox 是我目前唯一的浏览器。

When I use textContent, the alert box appears but it is blank. When I use value, the alert box appears and says "Undefined" When I use innerHTML, all the HTML appears including the tags.

当我使用 textContent 时,会出现警告框,但它是空白的。当我使用 value 时,会出现警告框并显示“未定义”当我使用 innerHTML 时,所有 HTML 都会出现,包括标签。

Also, I understand that textContent only runs in FF and for cross browser compatibility you need to do something like innerText and textContent but textContent is not working in FF. There is no jquery on this app

另外,我知道 textContent 仅在 FF 中运行,为了跨浏览器兼容性,您需要执行诸如 innerText 和 textContent 之类的操作,但 textContent 在 FF 中不起作用。此应用程序上没有 jquery

What is the correct cross browser way to get contents of textarea! Thanks for any suggestions.

获取textarea内容的正确跨浏览器方式是什么!感谢您的任何建议。

回答by Raheel Hasan

For textarea, you could only use .valuein your scenario (I tested your given code and it works fine). .

对于textarea,您只能.value在您的场景中使用(我测试了您给定的代码并且它工作正常)。.

Also,

还,

1) keep in mind that you call this function addProduct()ONLYafter your element is mentioned in the code, otherwise it will be undefined.

1) 请记住,addProduct()只有在代码中提到您的元素后才调用此函数,否则它将是undefined.

2) there must notbe another element with id as productdescript

2)不能有另一个元素id as productdescript

3) there must not be a JS variablecalled productdescript

3)一定不能有JSvariable调用productdescript

回答by Superboleta

This are your code?

这是你的代码?

you write document.getElementByID....and the "D" should be written lowercase "d"

你写document.getElementByID....的“D”应该写成小写的“d”

document.getElementById('productdescript').textContent;