jQuery/javascript different behaviours with user click and programatically click a checkbox

北城余情 提交于 2019-12-21 20:42:32

问题


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();


来源:https://stackoverflow.com/questions/4428292/jquery-javascript-different-behaviours-with-user-click-and-programatically-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!