我什么时候使用.val()vs .innerHTML? [英] When do I use .val() vs .innerHTML?
问题描述
在JQuery中,当试图访问元素时,我看到如果我有一个表单(可以说是 textarea
),并且我想获取 text
里面,我必须使用 $(textarea)。val();
相反,如果我有一个 h1
元素,我必须使用 $(h)[0] .innerHTML;
为什么会出现这种情况? h1.val()/ textarea.innerHTML不起作用
.val()
用于获取/替换jQuery中的输入元素值,JS中的替代值是 .value
。 使用
innerHTML
或使用jQuery的 .html()
以获取/替换元素内的整个标记,而不是输入元素。
text()
几乎用于与JS innertHTML
相同,只有它获取/替换元素内部的文本,而不是所有的标记等。它与JS innerText
有关 innerHTML , innerText , val() , text() , html()
In JQuery when trying to access elements, I see that if I have a form (lets say a textarea
), and I want to get the text
inside of it, I must use $("textarea").val();
Instead if I have a h1
element, I must use $("h")[0].innerHTML;
Why is this the case? h1.val()/textarea.innerHTML do not work
.val()
is used to get/replace input elements values in jQuery, alternative in JS is .value
.
innerHTML
or jQuery's .html()
is used to get/replace the whole markup inside an element, not input elements.
text()
is used almost the same as JS innertHTML
, only it gets/replaces the text inside an element, not all the tags etc. It's bassically the equivalent of JS innerText
Reference links about innerHTML, innerText, val(), text(), html()
这篇关于我什么时候使用.val()vs .innerHTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!