What is the difference between this.click () and $ (this) .click ()?

In the end, I decided that this was not a problem that I especially needed to fix, but it bothered me that I did not understand why this was happening.

Basically, I have some checkboxes, and I want users to be able to select a certain number of them. I use the following code to achieve this effect.


$j( function () {
    $j('input[type=checkbox].vote_item').click( function() {
        var numLeft = (+$j('#vote_num').text());
        console.log(numLeft);
        if ( numLeft == 0 && this.checked ) {
            alert('I\'m sorry, you have already voted for the number of items that you are allowed to vote for.');
            return false;
        } else {
            if ( this.checked == true ) {
                $j('#vote_num').html(numLeft-1);
            } else {
                $j('#vote_num').html(numLeft+1);
            }
        }
    });
});

And when I tested it, I noticed that if I used:


$j('input[type=checkbox]').each( function () {
    this.click()
});

Javascript reacted as I expected, however when used with:


$j('input[type=checkbox]').each( function () {
    $j(this).click()
});

Actually the counter is an UP counter.

I understand that this is not the safest way to count the counters, but I have a server-side error check that prevents entering into the database a larger amount of the required amount, which is the reason that I decided that this is actually not required.

: $j , jQuery noConflict...

+3
3

, , , , , click.

Google "jquery checkbox click event raise" , , .

http://www.bennadel.com/blog/1525-jQuery-s-Event-Triggering-Order-Of-Default-Behavior-And-triggerHandler-.htm

, , :

$j('input[type=checkbox].vote_item').click( 
function() 
{
    var maxNumberOfChoices = 5;

    //get number of checked checkboxes. 
    var currentCheckedCount = $j('input[type=checkbox].vote_item :checked');

    if(currentCheckedCount > maxNumberOfChoices)
    {
        //It useful if you show how many choices user can make. :)
        alert('You can only select maximum ' + maxNumberOfChoices + ' checkboxes.');
        return false;
    }

    return true;
});
+3

$(this) jQuery ( ), DOM.

+6

this.click() DOM click().

$(this).click()calls the jQuery method click(), which does more than just calling the browser method: see the implementation of the function triggerfor details.

+3
source

Source: https://habr.com/ru/post/1711619/


All Articles