简体   繁体   中英

How can I use the keyword $(this) in place of class selector - jQuery?

I have the following code in jQuery -

$(".new_makes_button").click(function(){
    if($(".new_makes_button:checked").length == 0) {

So how can I replace class selector ".new_makes_button" in second line of above code with $(this)? I am just in search of correct syntax. Here I have several checkboxes with class "new_makes_button" and clicking on any of it, I am checking when all the checkboxes will be unchecked then run the following code.

Try this:

if (!$(this).is(":checked")) {
    ...
}

You can just look at the checked property directly on the clicked on item like this:

if (!$(this).prop("checked")) {
    // code here for when the item is not checked
}

Once you have the DOM element (which you have in this ), there is no need to use further selectors as you can just examine the properties of that item directly.

This will check if the current item, is checked. The current item is the Event source element. $(this) inside the callback is a reference to a single element.

if(this.checked === false) {

}

But, if you want to find out if none of the elements with .new_makes_button are checked then you can use jQuery.

$(".new_makes_button").click(function() {
   // $(this) at this point is a reference to a 
   // single element. To get Them all you may do this:
   var total = 0;
   $(".new_makes_button").each(function(index, element) {
     if(this.checked === true) {
       total++;
     }
   });
   alert("Total checked item" + (total).toString());
});

example

how can I replace class selector ".new_makes_button" in second line of above code with $(this)?

If you really want to use this object, then you can, however, it isn't not correct syntax to not use $(this) .

To use this inside that method and have it reference an array of .new_makes_button elements, you can change it's value using bind . Here in this example, this will reference a jQuery object.

$(".new_makes_button").click(function(e) {
  // here `this` is a jquery object!
  // no need to call the `$`
  console.log(this.length);
}.bind($(".new_makes_button")));

example

Shortest possible solution

$(".new_makes_button").click(function(e) {
  if(this.filter(':checked').length == 0) {
     // handle condition        
   }
}.bind($(".new_makes_button")));

In jQuery, the element being acted upon is often passed to the function parameter of a jQuery function as this. It can be made into a jQuery element object by using$(this) in the function parameter, ex:

$('.new_makes_button').click(function(){

$(this).animate({paddingLeft: $(this).width()}, 200);

});

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