【问题标题】:Jquery selector to do text() but without class or id?Jquery 选择器做 text() 但没有类或 id?
【发布时间】:2016-06-20 18:31:32
【问题描述】:
<h1>
    <br>
    USA
    <br>
    <br>
    <p style="margin-top:13px;" class="glyphicon glyphicon-chevron-down"></p>
    <br>
    <br>
    Canada 
</h1>

在不改变上面的 HTML 的情况下,如何使用 jQuery 选择器获取 Canada 的值?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

如果你想获取最后一个文本节点值,那么试试这个

var h1 = document.querySelector("h1");
var childNodes = h1.childNodes;
console.log(childNodes[childNodes.length -1 ].nodeValue);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><br>USA<br><br><p style="margin-top:13px;" class="glyphicon glyphicon-chevron-down"></p><br><br>Canada </h1>

等效的 jquery 将是

var h1 = $("h1")[0];

【讨论】:

  • 嘿,jquery 版本返回的是 h1 选择器而不是值。
  • @AlienXu 是的,您需要在其中添加下两行。我刚刚演示了使用 javasript 和 jquery 获取h1,您仍然需要迭代它们的子节点。基本上,jquery 对 textnodes 帮助不大。
【解决方案2】:

如果标记风格一致——不易改变,可以使用xpath

https://developer.mozilla.org/en-US/docs/Web/XPath

【讨论】:

    【解决方案3】:

    你也可以这样做:

    var value = $('h1').contents().filter(function() {
        return this.nodeType == 3;
    })[1];
    

    这里我使用nodeType == 3,它选择文本节点。

    https://jsfiddle.net/54tw4nw0/

    【讨论】:

      【解决方案4】:

      给你:

      var afterP;
      
      var text = $('h1').contents().filter(function() {
          if (this.nodeName == "P") {
              afterP = true
          }
      
          return afterP && this.nodeType == 3;
      }).text();
      
      console.log(text);
      

      Get the text after span element using jquery复制和增强的解决方案

      【讨论】:

        【解决方案5】:

        试试:

        var text = $("h1").html();
        alert(text.substring(text.lastIndexOf("<br>") +4));
        

        Working Fiddle

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-03-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-04-04
          • 1970-01-01
          • 1970-01-01
          • 2015-08-31
          相关资源
          最近更新 更多