开发者

How to make an event handler fire only once in JQuery for the Selectors with multiple items?

开发者 https://www.devze.com 2023-02-20 22:26 出处:网络
I have following JQUERY code. <script type=\"text/javascrip开发者_JS百科t\"> $(\".voteup\").click(function(){

I have following JQUERY code.

<script type="text/javascrip开发者_JS百科t">
    $(".voteup").click(function(){
        alert($(this).parents(".webresource").attr("id"));
    });
</script>

The page has 4 elements with classname voteup. But when I click on one of them, alert is displayed four times. I would think that there is only one click so the event handler function would execute only once.

What do I do to ensure that the event handler function is executed only once.


.one() binds an event handler and the unbinds it on its first execution.

$('.upvote').one('click', function() {
   ...
});

Also, I'd make sure it's not being bound multiple times somehow as Ender suggests in your comments.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号