简体   繁体   中英

JQuery event listening fired twice

I am doing a .NET Core 2 application that uses also JQuery.

In a html button I have, I am doing a JQuery function to cacth the click event. This function, for some reason is firing twice. Anyone can help me understand why?

Thanks in advance!!

HTML code:

<div class="menu">
        <button class="btn btn-default" id="seeds">Seeds</button>
</div>

JQuery (inside a .js file):

$("body").on("click", "#seeds", function () {
    alert('click fired');
});

Please keep in mind that you could register multiple event handler for the same event in jQuery. So if your handler is registered twice, your handler would run on a single click event. You can remove a listener by using the off method

$("body").off("click");

But i would suggest to register the handler directly on your element:

$("#seeds").on("click", function(){
    alert('click fired');
});

I tried to reproduce your problem, using the same code you posted, but it didn't happened. Maybe, you are registering this event twice.

And you can register the event directly to the element, like this:

$("#seeds").on("click", function(){
    alert('click fired');
});

Or, like this:

$("#seeds").click(function(){
    alert('click fired');
});

May be you have used same id twice. So please verify that id.

You can use below code as well,

 $("#seeds").click(function(){ alert('click event'); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="menu"> <button class="btn btn-default" id="seeds">Seeds</button> </div> 

Thank you all for your inputs and help. I now am triggering the function directly on the element, as all of you suggested.

However I discovered the problem. How dummy am I?? I had the link to my .js file twice in my html layout file. Duuh for me!!

Thank you all again for taking the time to help me!!

Best!!

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