click事件多次触发问题,怎么办? [英] click event fires multiple times issue, how to?

查看:136
本文介绍了click事件多次触发问题,怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按钮.当我单击它时,我在DOM上附加了一些按钮.

I have a button. when I click it I am appending some buttons to the DOM.

我遇到的问题是我要追加触发的那些按钮多次.

The issue I have is that those buttons that I am appending fire multiple times.

$(el).on('click', function (e) {
    key();
});

function key() {
    $(document).on('click', '#key li', function () {
        console.log($(this));
    });
}

第一次调用key()时,console.log触发一次

First time key() is called, the console.log fires once

我第二次呼叫key()时,console.log会触发两次

The second time I call key() the console.log fires twice

依此类推

我尝试添加$(document).find('#key li').unbind('click'),但这似乎不起作用

I've tried adding $(document).find('#key li').unbind('click'), but that doesn't seem to work

有什么想法吗?

这是一个 jsfiddle示例(如下所示).

Here is an jsfiddle example (shown below).

$('button').on('click', function () {
    $('.cont').remove();
    $('.container').remove();
    var html = '<button class="cont">click</button><div class="container">placeholder</div>';
    $('body').append(html);
    key();
});

$(document).on('click', '.cont', function () {
    var html = '<div id="but_placeholder"><button class="one">1</button><button class="two">2</button><button class="three">3</button></div>';
    $('.container').html(html);
});

function key() {
    $(document).on('click', '#but_placeholder button', function () {
        $('input').val($('input').val() + $(this).html());
    });
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input" />
<button>test</button>

要进行复制,请单击test按钮,然后在click上,然后单击一个1 2 3并重复该过程

To reproduce, click on the test button, then on the click,then one 1 2 3 and repeat the process

您会注意到,第二次执行此过程时,文本会翻倍

You will notice that the second time you go through the process the text doubles

推荐答案

执行此操作

function key() {
    $('#key li').unbind('click');
    $('#key li').bind('click', function () {
        console.log($(this));
    });
}

或者您可以做

function key() {
    $('#key').find('li').unbind('click');
    $('#key').find('li').bind('click', function () {
        console.log($(this));
    });
}

我想第二个肯定会工作.

I guess the second one will surely work.

更新方法

function key() {
    $(document).off('click', '#but_placeholder button');
    $(document).on('click', '#but_placeholder button', function () {
        $('input').val($('input').val() + $(this).html());
    });
}

这篇关于click事件多次触发问题,怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆