最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery if and else statements both executing - Stack Overflow

programmeradmin1浏览0评论

I've got a script that will add a class to an element if the page title matches the textual value of an <a> tag. The else statement in my script is to cover when none of the page titles match the nav items and the active link is assigned to the Home menu item (i.e. the first in the nav bar).

I have a menu that's like this:

<ul class='menu'>
    <li> <a href="#">Home</a> </li>
    <!-- Page title - My Cool Website -->
    <li> <a href="#">About Us</a> </li>
    <!-- Page title - About Us -->
    // etc....
</ul>

Here's the script:

$(document).ready(function () {
    var title = $(document).attr("title");
    $(".menu li a").each(function (e) {
        var a = $(this).text();
        var exists = title.match(a);
        if (exists) {
            $(this).addClass("active");
        } else {
            $(".menu li a").first().addClass("active");
        }
    });
});

The if and else statements seem to be executing so both the first and the matched elements now have an active class added to them.

I've tried using stopPropagation(); and return false at the end of my statement but to no success.

Can anyone tell me the reason why both are executing? I assume I'm not jumping through the DOM elegantly but javascript is a little rusty.

I've got a script that will add a class to an element if the page title matches the textual value of an <a> tag. The else statement in my script is to cover when none of the page titles match the nav items and the active link is assigned to the Home menu item (i.e. the first in the nav bar).

I have a menu that's like this:

<ul class='menu'>
    <li> <a href="#">Home</a> </li>
    <!-- Page title - My Cool Website -->
    <li> <a href="#">About Us</a> </li>
    <!-- Page title - About Us -->
    // etc....
</ul>

Here's the script:

$(document).ready(function () {
    var title = $(document).attr("title");
    $(".menu li a").each(function (e) {
        var a = $(this).text();
        var exists = title.match(a);
        if (exists) {
            $(this).addClass("active");
        } else {
            $(".menu li a").first().addClass("active");
        }
    });
});

The if and else statements seem to be executing so both the first and the matched elements now have an active class added to them.

I've tried using stopPropagation(); and return false at the end of my statement but to no success.

Can anyone tell me the reason why both are executing? I assume I'm not jumping through the DOM elegantly but javascript is a little rusty.

Share Improve this question edited May 6, 2015 at 9:26 Tushar 87.2k21 gold badges163 silver badges181 bronze badges asked May 6, 2015 at 9:25 WebDevDannoWebDevDanno 1,1222 gold badges22 silver badges50 bronze badges 4
  • Can you create jsFiddle of the problem – Tushar Commented May 6, 2015 at 9:27
  • 1 That is because you have multiple <a>s. Some or the other a will satisfy if() or else – Shaunak D Commented May 6, 2015 at 9:27
  • @Tushar the script is designed to work over multiple pages with a <title> tag so I'm unable to provide a working jsFiddle. – WebDevDanno Commented May 6, 2015 at 9:28
  • 1 I guess you have to declare the exist variable outside of the each function – Kilian Stinson Commented May 6, 2015 at 9:28
Add a ment  | 

4 Answers 4

Reset to default 7

The problem is your each loop, assume you found the match in the second a but still the each loop continues so the first element will again get the class

$(document).ready(function () {
    var title = $(document).attr("title");
    var exists;
    $(".menu li a").each(function (e) {
        var a = $(this).text();
        exists = title.match(a);
        if (exists) {
            $(this).addClass("active");
            return false;
        }
    });
    if (!exists) {
        $(".menu li a").first().addClass("active");
    }
});

The reason behind your issue is that you have mutiple anchor <a>s, some or the other will satisfy an if() or else if you add these conditions inside the loop.

The exists should be outside the each loop. You need to check if no elements match the title after the elements are traverse i.e. outside the loop.

$(document).ready(function() {
    var exists = false;
    var title = $(document).attr("title");
    $(".menu li a").each(function(e) { 
        var a = $(this).text(); 
        exists = title.match(a);
        if(exists) {
            $(this).addClass("active"); 
                return false; //break if statement matches.            
        }
    });
    if(!exists){
        $(".menu li a").first().addClass("active");
    }
});

Your 'exists' variable reinitialize for every item. That's the problem. Use this code instead:

    $(document).ready(function () {
    var title = $(document).attr("title");
    var exists = false;
    $(".menu li a").each(function (e) {
        var a = $(this).text();

         if(title.match(a))
         {
         exists = true;
         return false;
         }
       });
    if (exists) {
      $(this).addClass("active");
     } 
     else {
      $(".menu li a").first().addClass("active");
     }
});

Try this:

$(document).ready(function() {
    var title = $(document).attr("title");
    $(".menu li a").each(function(e) { 
        var a = $(this).text(); 
        var exists = title.match(a);
        if(exists) {
            $(this).addClass("active");             
        } 
    });
    $(".menu li:first-child a").addClass("active")  
});  

发布评论

评论列表(0)

  1. 暂无评论