简体   繁体   中英

Better way to write this jquery?

Is there a better way to write this so that I'm not "re-selecting" #abc?

    $('#abc').click( function(e){
        e.preventDefault();
        $('#abc').addClass('someclass');
    });

I'm new to jQuery but try the following:

$(this).addClass('someclass');

this refers to the element that the callback is being called for.

$('#abc').click( function(e){
    e.preventDefault();
    $(this).addClass('someclass');
});
var abc = $('#abc');
abc.click( function(e){
    e.preventDefault();
    abc.addClass('someclass');
});

在回调中使用this

$(this).addClass("someclass");

Use this -

$('#abc').click( function(e){
        e.preventDefault();
        $(this).addClass('someclass');
    });

Check this jsFiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM