js中的innerText、innerHTML、属性值、value与jQuery中的text()、html()、属性值、val()总结

js与jQuery获取text、html、属性值、value的方法是不一样的。

 <p id="test">这是段落中的 <b>粗体</b> 文本。</p> 
有上面这样一个文本框

js获取text、html、属性值、value的方法:
document.getElementById("test").innerText;
document.getElementById("test").innerHTML;
document.getElementById("test").id;
document.getElementById("test1").value;

jQuery
获取text、html、属性值、value的方法:
$("#test").text()或者$("#test").innerText
$("#test").html()或者$("#test").innerHTML
$("#test").attr("id")
$("#test").attr("value")或者$("#test1").val()或者$("#test1").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").innerTEXT
); });

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值获取

原文地址:https://www.cnblogs.com/mlbblkss/p/7135871.html