jQuery: How to find elements *without* a certain c

2019-06-19 16:55发布

Why does this fail...

$( 'div.contactAperson input' ).not( 'input.hadFocus' ).focus(function() {
    $(this).attr('value', '' );
});

...it's meant to sniff out input's that have not got the class .hadFocus and then when one of that subset receives focus it should zap the value to null.

Right now, input values are always getting zapped -- the test .not( 'input.hadFocus' ) is failing to stop execution.

Btw, preceding the above code is the following code, which is working fine:

$( 'div.contactAperson input' ).focus(function() {
    $( this ).addClass( 'hadFocus' );
});

Thanks for any cleverness - cheers, -Alan

2条回答
Luminary・发光体
2楼-- · 2019-06-19 17:39

You need the handler to run based on the current state of the element - not the state when it was bound. You probably need to use a live binding.

Try something like this:

$('div.contactAperson input:not(.hadFocus)').live('focus', function() {
    $(this).attr('value', '' );
});
查看更多
【Aperson】
3楼-- · 2019-06-19 17:39
$( 'div.contactAperson > :input' ).not( ':input.hadFocus' ).focus(function() {
    $(this).attr('value', '' );
});

good luck

查看更多
登录 后发表回答