由于多个类,jQuery和If语句不匹配

我有DOM元素我想通过添加一个类“noEdit”从.click函数中排除我遇到的问题是这些元素中的一些有多个类,即:

 // <-- wont work  // <-- works fine 

和jQuery:

 $('td').click( function(){ if($(this).attr('class') != "noEdit"){ alert('do the function'); }); 

想法?

如果使用attr()查询class属性,它只是将值作为单个字符串返回。 然后,您的第一个

条件失败,因为您的代码将尝试进行比较

 "firstCol noEdit" != "noEdit" 

返回true(因为它们不相等)并导致显示警报。

您将要查看hasClass()函数,它会为您解析类列表并检查属性中是否存在给定类:

 $('td').click(function() { if (!$(this).hasClass("noEdit")) { alert('do the function'); } }); 

如何使用属性filter:

 // != means 'not exactly matching', whereas *= means 'contains' $('td[class!=noEdit]').click( function(){ alert('do the function'); }); 

你可以使用jQuery的not()遍历来清理它:

 $('td').not('.noEdit').click(function() { alert('do the function'); });