简体   繁体   English

jQuery事件侦听触发两次

[英]JQuery event listening fired twice

I am doing a .NET Core 2 application that uses also JQuery. 我正在做一个也使用JQuery的.NET Core 2应用程序。

In a html button I have, I am doing a JQuery function to cacth the click event. 在我拥有的html按钮中,我正在做一个JQuery函数来封装click事件。 This function, for some reason is firing twice. 由于某种原因,此功能会触发两次。 Anyone can help me understand why? 任何人都可以帮助我理解为什么吗?

Thanks in advance!! 提前致谢!!

HTML code: HTML代码:

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

JQuery (inside a .js file): jQuery(在.js文件中):

$("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. 请记住,您可以为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 您可以使用off方法删除侦听器

$("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. 可能是您两次使用相同的ID。 So please verify that id. 因此,请验证该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. 我的html布局文件中有两次指向.js文件的链接。 Duuh for me!! Duuh对我来说!!

Thank you all again for taking the time to help me!! 再次感谢大家花时间帮助我!!

Best!! 最好!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM