简体   繁体   English

如果 div 包含的 href 包含带有 jquery 的特定字符串,则更改其背景颜色

[英]change background color of div if it contains an href that contains a specific string with jquery

I'm trying to take a list of hrefs and change the color of one of them if a word in the current url exists in the href.如果当前 url 中的一个单词存在于 href 中,我正在尝试获取一个 href 列表并更改其中一个的颜色。 The challenging part is that all of the divs have the same class and can't be changed.具有挑战性的部分是所有 div 都具有相同的 class 并且无法更改。 Everything I've tried either changes all of them or none of them.我尝试过的一切要么全部改变,要么都不改变。 Here's the code I have:这是我的代码:

<div id="links">
    <div class="box"><a href="example.com/carolina">Link One</a></div>
    <div class="box"><a href="example.com/virgina">Link Two</a></div>
    <div class="box"><a href="example.com/georgia">Link Three</a></div>
</div>


<script type="text/javascript">
    $( document ).ready(function() {
    var pathArray = window.location.pathname.split('/');
    $(".box").each(function(){
        if (window.location.href.indexOf(pathArray[1]) > -1) {
            $(this).css('background', 'red');
        }
    });
});
</script>

Assuming that the current URL is: example.com/virgina/contact.html I would expect the middle div's background to change to red.假设当前 URL 是:example.com/virgina/contact.html 我希望中间 div 的背景变为红色。 What am I missing?我错过了什么?

You're comparing current URL to the current URL, not the current URL to the link HREF.您正在将当前 URL 与当前 URL 进行比较,而不是当前 URL 与链接 HREF。

Change改变

if (window.location.href.indexOf(pathArray[1]) > -1) {

to

if ($(this).children('a').attr('href').indexOf(pathArray[1]) > -1) {

Or you could replace the whole each() with just:或者您可以将整个each()替换为:

$('.box:has(a[href*="'+pathArray[1]+'"]').css('background', 'red');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM