【问题标题】:jQuery selector excluding hyperlinksjQuery 选择器不包括超链接
【发布时间】:2013-11-07 14:45:50
【问题描述】:

好的,这应该是显而易见的......

我有一个带有一些文本和链接的 div。 我想更改文本的背景颜色,但链接。

<div id="one">
    Foo bar <a href="http://stackoverflow.com">link</a> barfoo 
</div>

不明白为什么这不起作用...

$("#one:not(a)").css("background-color", "red");

$("#one, #one *:not(a)").css("background-color", "red");

$("#one").find("a").not(this).css("background-color", "red");

将背景颜色设置为与我想要的完全相反..

谢谢。

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:

    你试过了吗?

    $("#one").not("a").css("background-color", "red");
    $("a").css("background-color", "white");
    

    因为“#one”是包含的 div,它会为整个容器着色。在锚点后记上进行选择是保留颜色的方法。

    否则,您可以添加如下内容,然后仅选择跨度:

    <div id="one">
        <span>Foo bar</span> <a href="http://stackoverflow.com">link</a> <span>barfoo </span>
    </div>
    

    但这并不完全符合语义。如果你正在做一些更真实的世界,少一点 barfoo,它可能更实用。

    【讨论】:

      【解决方案2】:

      您遇到的问题是除了链接之外,您的 div 中没有其他元素。

      将您的 HTML 更改为

      <div id="one">
          <span>Foo bar </span><a href="http://stackoverflow.com">link</a><span> barfoo </span>
      </div>
      

      那你就可以了

      $("#one :not(a)").css("background-color", "red");
      

      (注意空格)。

      您可以自动插入跨度:

      $("#one").html(function(_,h){
        return '<span>'+h.replace(/<a\s+.*?<\/a>/g,function(s){
             return '</span>'+s+'<span>'
        })+'</span>';
      });
      $("#one :not(a)").css("background-color", "red");
      

      Demonstration

      另一种解决方案是给 div 一个红色并且给你的链接一个不透明的颜色:

      $("#one").css("background-color", "red");
      $("#one a").css("background-color", "white"); // give the color of what's behind the div
      

      【讨论】:

      • 感谢dystroy,这是有道理的。但是,如果可能的话,我想避免用其他元素包装文本。此外,如果我可以为 whole div 内容或 only 链接设置背景,那么相反的做法似乎是合乎逻辑的。
      • 你需要有一个元素来应用你的风格。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-06
      • 1970-01-01
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多