jQuery if属性包含某个值

jQuery if属性包含某个值,jquery,Jquery,在这里完全是一片空白。 希望你能帮忙 当属性“href”不以#overlay开头时,我将如何更改此参数 if(this.getTrigger().attr("href")){ // stuff in here } 谢谢你们这些了不起的人。 Kevin您可以使用,或者: 或: 或正则表达式方法: if(!/^#overlay/.test(this.getTrigger().attr(“href”)){ } 使用匹配(RegEx)测试href是否以#overlay开头,然后将其取反: if (!t

在这里完全是一片空白。 希望你能帮忙

当属性“href”不以#overlay开头时,我将如何更改此参数

if(this.getTrigger().attr("href")){
// stuff in here
}
谢谢你们这些了不起的人。 Kevin

您可以使用,或者:

或:

或正则表达式方法:

if(!/^#overlay/.test(this.getTrigger().attr(“href”)){
}
使用
匹配(RegEx)
测试href是否以
#overlay开头,然后将其取反:

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

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

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


你可以这样检查

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

如果要使用jQuery选择器:

if(this.getTrigger().is('a:not([href^="#overlay]")')) {
  // stuff in here
} 
编辑:如果您已经只有一个项目,并且希望检查其
href
值,那么选择器解决方案的性能比仅将属性切片与
“#overlay”
进行比较要差,如其他答案所示。我刚刚发布了我的解决方案,以表明有多种方法可以做到这一点。

使用
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");
}

href=$(“#myLink”).attr('href');
如果(href.toLowerCase().indexOf('someaction')>=0){
警报(“在href上发现了某些操作”);
}

@Kevin:我无意对@chiborg不敬,我强烈要求你重新考虑你的方法<与标准字符串比较方法相比,code>is()
的性能非常差。这样考虑一下,jQuery必须解析选择器字符串的每一部分,并在得出结论之前运行许多条件检查。这里的所有其他答案都大大优于此解决方案。@Andy E:没有不尊重:)我已经更新了我的文本,以澄清我的解决方案对于此特定用例来说是次优的。我认为您应该接受Andy E的答案。这是最正确/最完整的。
子字符串
是最快的(考虑到失败和成功的搜索):@galambalaz:谢谢-我首先使用了
切片
/
子字符串
方法,因为我知道它们比字符串搜索快,但是有一些具体的东西来展示这一点是很好的。我认为应该是:indexOf(“#overlay”)!=-1.
if(this.getTrigger().attr("href").indexOf('#overlay') != 0) {
}
if(this.getTrigger().is('a:not([href^="#overlay]")')) {
  // stuff in here
} 
<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");
}