jQuery/javascript different behaviours with user c

2019-04-12 03:38发布

问题:

A bit hard to explain, so I've set up a jsFiddle here.

Basically, I have some behaviour triggered when a user clicks a checkbox. In another place I'm trying to programatically click the check box and I need to see the exact same behaviour. It doesn't work, seemingly something to do with the order of the click and determining the checked attribute.

How can I get the behaviour I'm looking for without resorting to a hack?

回答1:

I tend to use change handler here instead (since jQuery normalizes the behavior, it doesn't require a blur), then fire that event like this:

$('span').click(function() { $('.test').click().change(); });

Then, you're explicit about the order...and you don't have the issue of the native action vs event handler order, you can test it out here.



回答2:

You don't need to put javascript for this behaviour... just use this html syntax :

<input type="checkbox" id="myid" />&nbsp;<label for="myid">My Label</label>

If you want to add javascript listners, you can add change or click to input field.

:)

OR you should do that using jquery :

$('span').click(function() { $('.test').trigger('click'); });


回答3:

I had the same problem and fixed it calling the javascript click function instead of jQuery one like this:

$('.test')[0].click();