標籤:jquery 結果 text innertext inpu click nbsp ext --
js與jQuery擷取text、html、屬性值、value的方法是不一樣的。
js與jQuery,text與innerText擷取(<!---->中為結果)
html: <p id="test">這是段落中的 <b>粗體</b> 文本。</p> <button id="btn10">jQuery顯示text</button> <!--Text: 這是段落中的 粗體 文本。--> <button id="btn11">jQuery顯示 innerTEXT</button> <!--Text: undefined。--> <button id="btn12">js顯示 innerTEXT</button> <!--Text: test-->
js: $("#btn10").click(function(){ alert("Text: " + $("#test").text()); }); $("#btn11").click(function(){ alert("Text: " + $("#test").innerText); }); $("#btn12").click(function(){ alert("Text: " + document.getElementById("test").id); });
js與jQuery,html與innerHTML擷取
html:<p id="test">這是段落中的 <b>粗體</b> 文本。</p> <button id="btn20">jQuery顯示 HTML</button> <!--HTML: 這是段落中的 <b>粗體</b> 文本。 --> <button id="btn21">jQuery顯示 innerHTML</button> <!--HTML: undefined --> <button id="btn22">js顯示 innerHTML</button> <!--HTML: 這是段落中的 <b>粗體</b> 文本。 -->
js: $("#btn20").click(function(){ alert("HTML: " + $("#test").html()); }); $("#btn21").click(function(){ alert("HTML: " + $("#test").innerHTML); }); $("#btn22").click(function(){ alert("HTML: " + document.getElementById("test").innerHTML); });
js與jQuery,屬性值擷取
html:
<button id="btn30">js擷取Id的屬性值</button> <!--id: test --> <button id="btn31">jQuery擷取Id的屬性值</button> <!--id: test -->
js: $("#btn30").click(function(){ alert("id: " + document.getElementById("test").id); }); $("#btn31").click(function(){ alert("id: " + $("#test").attr("id")); });
js與jQuery,value擷取
html:<button id="btn40">js擷取input標籤的value值</button> <!--value: aaa --> <button id="btn41">jQuery擷取input標籤的value值(val())</button> <!--value: aaa --> <button id="btn42">jQuery擷取input標籤的value值(attr("value"))</button> <!--value: aaa -->
js: $("#btn40").click(function(){ alert("value: " + document.getElementById("test1").value); }); $("#btn41").click(function(){ alert("value: " + $("#test1").val()); }); $("#btn42").click(function(){ alert("value: " + $("#test1").attr("value")); });
注意:jQuery中的val()方法只能用於input元素的value值擷取
js中的innerText、innerHTML、屬性值、value與jQuery中的text()、html()、屬性值、val()總結