簡體   English   中英

如果 div 包含的 href 包含帶有 jquery 的特定字符串,則更改其背景顏色

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

如果當前 url 中的一個單詞存在於 href 中,我正在嘗試獲取一個 href 列表並更改其中一個的顏色。 具有挑戰性的部分是所有 div 都具有相同的 class 並且無法更改。 我嘗試過的一切要么全部改變,要么都不改變。 這是我的代碼:

<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>

假設當前 URL 是:example.com/virgina/contact.html 我希望中間 div 的背景變為紅色。 我錯過了什么?

您正在將當前 URL 與當前 URL 進行比較,而不是當前 URL 與鏈接 HREF。

改變

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

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

或者您可以將整個each()替換為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM