jQuery和If语句由于多个类而无法匹配 [英] jQuery and If Statement Not Matching Because of Multiple Classes
问题描述
我有一些DOM元素,我想通过添加一个类"noEdit"从.click函数中排除,我遇到的问题是其中某些元素具有多个类,即:
I have DOM elements I'd like to exclude from a .click function by adding a class "noEdit" the problem I'm having is some of these elements have multiple classes ie:
<td class="firstCol noEdit"> // <-- wont work
<td class="noEdit"> // <-- works fine
还有jQuery:
$('td').click( function(){
if($(this).attr('class') != "noEdit"){
alert('do the function');
});
有想法吗?
推荐答案
如果用attr()
查询class
属性,它只是将值作为单个字符串返回.然后该条件对于您的第一个<td>
失败,因为您的代码将尝试进行比较
If you query the class
attribute with attr()
, it simply returns the value as a single string. The condition then fails for your first <td>
because your code will attempt to compare
"firstCol noEdit" != "noEdit"
哪个返回true(因为它们不相等),并导致显示警报.
Which returns true (since they're not equal) and causes your alert to display.
您将改为查看hasClass()
函数,该函数为您解析类列表并检查属性中是否存在给定类:
You'll want to look at the hasClass()
function instead, which parses the class list for you and checks for the presence of the given class in the attribute:
$('td').click(function() {
if (!$(this).hasClass("noEdit")) {
alert('do the function');
}
});
这篇关于jQuery和If语句由于多个类而无法匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!