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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM