开发者

if statement syntax in Javascript jQuery .each function

开发者 https://www.devze.com 2023-01-29 17:26 出处:网络
(very new to JavaScript jQuery) Can an if statement contain a collection of other functions, specifically .each functions? If yes, is there something wrong with my implementation?

(very new to JavaScript jQuery)

Can an if statement contain a collection of other functions, specifically .each functions? If yes, is there something wrong with my implementation?

var string2 = "domain";
var mainpath = (window.location.href);

if (mainpath.indexOf(string2))  {

    $("#topnav a").each(function(){                         
        var thishref = $(this).attr('href');    
        $(this).attr({href: thishref + '?lnkid=tnav'}); 
    });

    $("#nav a").each(function(){                            
        var thishref = $(this).attr('href');    
        $(this).attr({href: thishref + '?lnkid=pnav'});
    });

}

What I want to do is run the code inside the if statement only when the page is at my domain (rather than inside the development space开发者_StackOverflow中文版 of a cms). -Thanks


sure it can. You are doing it basically correct. A suggestion:

Be explicit with your if conditional, so do something like

if (mainPath.indexOf(string2) !== -1) {...

}


yes, nothing wrong with it. but it can be easily tricked with the following URL:

http://www.other.tld/?domain


Perfectly valid to use an if to conditionally run code. Though there seems to be an issue with your condition:

if (mainpath.indexOf(string2))

The index of string2 within mainpath can be 0 which would prevent your code from executing and that's certainly not what you want.

Rather test like this:

if ( mainpath.indexOf > -1 ) ...


As a suggestion, you can add a query to each link like this:

$("#topnav a").each(function(){                         
    this.search = 'lnkid=tnav';    
});

There is no need for a roundabout way involving getting the href attribute, appending to it, and putting it back.

Demo: http://jsfiddle.net/3ZpMz/1/

0

精彩评论

暂无评论...
验证码 换一张
取 消