【问题标题】:How to make jQuery function execute only once, even if we declare it multiple times in a form?即使我们在一个表单中多次声明它,如何让 jQuery 函数只执行一次?
【发布时间】:2021-11-28 20:40:39
【问题描述】:

当您单击文档中具有特定类的按钮时,我有一个 jQuery 函数,它将执行某些操作。前任。下面。

$(document).on('click', '.tambah', function(){
  alert('tombol tambah telah ditekan');
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-md btn-success tambah">+ tambah</button>

假设它们位于名为“script.php”的同一脚本中。当我调用脚本一次时,单击该类的功能将执行一次,但是当我再次调用脚本时,当我单击按钮时它执行了两次。如何防止它执行多个?

【问题讨论】:

    标签: javascript php html jquery mongodb


    【解决方案1】:

    如果您正在调用执行绑定的函数,那么它可以堆叠。在这种情况下,您通常会先“解除绑定”

    $(document).unbind('click').on('click', '.tambah', function(){
      alert('tombol tambah telah ditekan');
    });
    

    【讨论】:

    • 开/关替换了绑定/取消绑定。我还建议使用命名空间处理程序。 $(document).off('click.someCustomNamespace').on('click.someCustomNamespace', () =&gt; {alert('...')})
    • 感谢您的回答,它对我有用。但不幸的是,在我看来,另一个答案是最合适的,因为它以功能为中心,而不是以事件为中心。
    • “stopImmediatePropagation”解决方案实际上是一种内存泄漏,虽然很小。随着时间的推移附加越来越多的事件处理程序。
    • @AlienWithPizza 这很漂亮。我不知道我们可以这样命名空间事件
    • 实际上是“最佳实践”,我认为您的解决方案比我发布的 stopImmediatePropagation 更好。但是在同一个事件上有多个处理程序,表明整个脚本已经不完美,所以 stopImmediatePropagation 是一个简单的解决方案。除此之外,它还具有在事件处理程序中决定是否要让事件冒泡的优势......只要事件处理程序没有被某种循环附加,内存就不应该那么大了;-)
    【解决方案2】:

    event.stopImmediatePropagation();[docs] 应该可以解决问题

    $(document).on('click','.tambah',function(event){
        alert('tombol tambah telah ditekan');
        event.stopImmediatePropagation();
    });
    $(document).on('click','.tambah',function(event){
        alert('tombol tambah telah ditekan');
        event.stopImmediatePropagation();
    });
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button type="button" class="btn btn-md btn-success tambah">+ tambah</button>

    【讨论】:

    • 虽然这确实有效,但它实际上是一个小的内存泄漏。实际上,这取决于处理程序中所做的事情,它可能最终成为一个大的。处理程序中使用的任何变量都将保留,直到事件被删除。
    猜你喜欢
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多