开发者

jQuery if attribute contains a certain value

Having a total mind blank here. Hoping you can help.

How would I alter this argument to be when the attribute 'href does not start with #overlay'...

if(this.getTrigger().attr("href")){
// stuff in her开发者_运维百科e
}

Thanks you wonderful people. Kevin


You can use slice, substring or substr:

if (this.getTrigger().attr("href").slice(0, 8) != "#overlay") {
}

or indexOf:

if (this.getTrigger().attr("href").indexOf("#overlay") != 0) {
}

or the regex test method:

if (!/^#overlay/.test(this.getTrigger().attr("href"))) {
}


If you want to use jQuery selectors:

if(this.getTrigger().is('a:not([href^="#overlay]")')) {
  // stuff in here
} 

Edit: In your case where you already have only one item and want to check its href value, the selector solution performs worse than just comparing a slice of the attribute to '#overlay' as the other answers here have shown. I just posted my solution to show there is more than one way to do it.


You could check this way

if(this.getTrigger().attr("href").indexOf('#overlay') != 0) {
}


Use indexOf():

<a id="myLink" href="http://company.com/?action=someAction">someAction</a>

href = $("#myLink").attr('href');

if(href.toLowerCase().indexOf('someaction') >= 0) {
    alert("someAction was found on href");
}


Use match(RegEx) to test if href starts with #overlay then negate it:

if (!this.getTrigger().attr("href").match(/^#overlay/)) {
    // stuff in here
}


Try this

String.prototype.startsWith = function(str){
    return (this.indexOf(str) === 0);
}

if(!this.getTrigger().attr("href").startsWith("#overlay")){
// stuff in here
}

Or

var check = "#overlay";
if(!this.getTrigger().attr("href").substring(0, check.length) === check){
// stuff in here
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜