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="noE开发者_如何学Cdit"> // <-- works fine
And the jQuery:
$('td').click( function(){
if($(this).attr('class') != "noEdit"){
alert('do the function');
});
thoughts?
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"
Which returns true (since they're not equal) and causes your alert to display.
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');
}
});
How about using an attribute filter:
// != means 'not exactly matching', whereas *= means 'contains'
$('td[class!=noEdit]').click( function(){
alert('do the function');
});
You can use jQuery's not() traversal to clean that up:
$('td').not('.noEdit').click(function() {
alert('do the function');
});
精彩评论