2010-11-08 76 views
2

我使用jQuery和我一样的循环:如何检查id名称是否包含某种模式?

$("span").each(function (index) { 
    var idname = $(this).attr('id'); 
    $("#" + idname).click(function() { 
     window.location.href = "http://" + $(this).attr('id') + "lin.gw"; 
    }); 

}); //end for click attachment to button 

我想遍历其中id包含*raid*的元素。它的语法是什么?

回答

5

使用attribute-contains selector

$("span[id*=raid]").click(function(){ 
    window.location.href = "http://"+ this.id +"lin.gw"; 
}); 
+0

这也是一个好方法。 – ward87 2010-11-08 11:42:22

+0

不错,谢谢! – Arman 2010-11-08 11:51:35

0

“喜欢”raid“'我认为你的意思是它包含”raid“。最简单的方法是测试一个正则表达式:/raid/.test(idname)。如果它是“raid”则返回true,如果不是,则返回false

0

你可以使用这个正则表达式。以下是正则表达式邮件匹配的示例。你可以编写自己的正则表达式,并检查“idname”是否包含“raid”。

function IsValidEmail(email) { var filter = /^([\w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([\w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$/; return filter.test(email); }

1

要做到这一点是使用filter删除元素的最好的方式,你不希望:

$("span").filter(function() { 
    if (this.id.toLowerCase().indexOf('raid') !== -1) { 
     return true; 
    } else { 
     return false; 
    } 
}).click(function(){ 
    window.location.href="http://"+this.id+"lin.gw"; 
}); 

它使用this.id(远比$(this).attr('id')更有效)并且使用单个呼叫而不是使用单个呼叫clickeach,这是更清晰,并提供轻微的性能提高。

相关问题