【问题标题】:Selecting a wrapping element in jQuery在 jQuery 中选择包装元素
【发布时间】:2016-02-28 01:26:34
【问题描述】:

我正在使用 jquery 和 nodejs 在一个非常旧的 Web 中进行一些过滤,并且我想选择由 p 包装的 b 元素。我的意思是只有那些用p 包裹而没有文字的人。

我要匹配的内容

<p><b>Some text</b></p>

我不想匹配的内容

<p>Some other text and some other elements <a>link</a><b>Some text</b> 
   and some more text of the parent p
</p>

你知道我可以选择第一个包装元素而不是第二个吗?有没有选择器可以选择这个?

【问题讨论】:

  • $('p b:empty') 试试这个
  • 检查这个小提琴jsfiddle.net/gd8mdL72
  • 谢谢@guradio,但这不是我想要的
  • 我想我不需要把它作为答案,因为你已经接受了一个已经很开心的编码

标签: javascript jquery css node.js


【解决方案1】:

您可以使用filter 方法:

$('p > b').filter(function() {
   return $(this.parentNode) // get the p element
                .contents() // get all the child nodes
                .not(this) // exclude the current `b` element
                .length === 0; 
});

http://jsfiddle.net/3v6w8a8y/

【讨论】:

  • 是的!这就是我想要的
【解决方案2】:

尝试使用:first-child 选择器

alert($("&gt;b:first-child", "p").text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<p><b>Some text</b></p>
What I don't want to match

<p>Some other text and some other elements <a>link</a><b>Some text</b> 
   and some more text of the parent p
</p>

【讨论】:

    【解决方案3】:

    不确定。你是这样的吗?

    HTML

     <p>Some other text and some other elements <a>link</a><b>Some text</b> 
        and some more text of the parent p</p>
     <p><b>Some text</b></p>
     <p>Some other text and some other elements <a>link</a><b>Some text</b> 
    

    以及父 p 的更多文本

    CSS

     p b:first-child:nth-of-type(1)
     {
        font-size:30px;
     }
    

    DEMO

    【讨论】:

    • 如果你想要的元素不是第二个...怎么办?
    【解决方案4】:

    使用substring()检查html()的前3个字母是否等于&lt;b&gt;

    $("p").each(function() {
       if ($(this).html().substring(0, 3) == "<b>") {
           // Do whatever
       }
    });
    

    JSFiddle Demo所示。

    【讨论】:

      猜你喜欢
      • 2012-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多