【问题标题】:jQuery select by Href inside specific DivjQuery 在特定 Div 中通过 Href 选择
【发布时间】:2010-09-01 18:09:08
【问题描述】:

我正在尝试选择一个特定的 来为其添加样式,但我的代码无法正常工作`

   var url=window.location.protocol + "//" + window.location.host+"/"+window.location.pathname;
jQuery('#accordion a[href*="'+url+'"]').css("font-weight", "bold");

该代码根本不起作用,它给出了未定义对象..所以这里有任何帮助:)

最好的问候 M赫加布

【问题讨论】:

  • 而您实际上在链接中使用了绝对 URL?
  • 是的..因为它是复杂的网站而不是简单的基于包的网站
  • 如果你想要一个特定的锚点,那么为什么不直接添加一个id 并使用它呢?

标签: jquery jquery-selectors


【解决方案1】:

window.location.pathname 已经以 / 开头,我不确定确切您的设置如何,但应该更像这样(主机和路径之间没有 /) :

var url=window.location.protocol + "//" + window.location.host+window.location.pathname;
jQuery('#accordion a[href*="'+url+'"]').css("font-weight", "bold");

【讨论】:

    【解决方案2】:

    我猜属性选择器是独立工作的。这对我有用。

    jQuery("#accordion").find("a[href*='" + url + "']").css("font-weight", "bold");

    如果您只需要定位子锚标记,您可以使用children() 方法而不是find() 方法。

    这对我有用:

    <html>
    <head>
    <title>Nithesh Chandra</title>
    <style>
    a.test { color: green; }
    </style>
    <script src="jquery.min.js" type="text/javascript" language="javascript">
    </script>
    <script language="javascript">
    $(function() {
      $('#testDiv').find("a[href*='http://google.com/']").addClass('test');
    });
    </script>
    </head>
    <body>
    <div id="testDiv">
      <a href="http://google.com/">Nithesh</a>
    </div>
    </body>
    </html>
    

    希望对你有帮助。

    【讨论】:

    • 实际上我尝试了 find ,它只有在我选择 (a) 时才有效,否则它什么也没给我:( 似乎 href 的选择在这里无法正常工作
    • 试试不带 *.我的意思是,如果您知道确切的 url,您总是可以将其匹配为“Equals”而不是“Contains”。更多选项请查看visualjquery.com
    • 不,它并不总是完全匹配..参数可能是从其他地方切换位置,或者参数可以获得不同的值..这就是我使用 like 或 contains 的原因
    猜你喜欢
    • 1970-01-01
    • 2010-11-07
    • 1970-01-01
    • 2020-03-29
    • 2018-12-03
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多