点击里面的点击功能导致警告信息显示不止一次- Jquery/Javascript

Click inside click function causing alert message showing more than once - Jquery/Javascript

本文关键字:不止一次 显示 Jquery Javascript 信息 功能 警告      更新时间:2023-09-26

我的问题有点难以解释,所以我做了一个jsfiddle。问题是。当我第一次点击<li>时,我得到一个警告消息。

现在我再次点击任何<li>,现在我得到2个警报。

首先点击任意input field --> then li --> then input field again --> then li again.

标记:

<input type='text' class='InputField'>
<input type='text' class='InputField2'>
<input type='text' class='InputField3'>
<div class="ranges FullBoxControl" style='display:none'>
    <ul>
        <li>This Month</li>
        <li>This Year</li>
        <li>Last 5 Years</li>
        <li>Last 10 Years</li>
        <li>Custom Range</li>
    </ul>
</div>

脚本代码:

$(".InputField").click(function()
{
    $('.FullBoxControl').show();
    $('.FullBoxControl').click(function()
    {
        alert('Greetings');
    });
});
$(".InputField2").click(function()
{
    $('.FullBoxControl').show();
    $('.FullBoxControl').click(function()
    {
        alert('Greetings');
    });
});
$(".InputField3").click(function()
{
    $('.FullBoxControl').show();
    $('.FullBoxControl').click(function()
    {
        alert('Greetings');
    });
});

JsFiddle Demo

问我你们是不是不懂

参考jsfield。每次在输入字段中单击,它都会绑定点击事件,因此有必要在公共函数中放入重复的代码并取消绑定点击事件,然后再绑定点击事件。

$(".InputField").click(function()
{
    fullbox();
});
$(".InputField2").click(function()
{
    fullbox();
});
$(".InputField3").click(function()
{
    fullbox();
});
function fullbox(){
    $('.FullBoxControl').show();
    $('.FullBoxControl').unbind("click");
    $('.FullBoxControl').click(function()
    {
        alert('Greetings');
    });
}

使用unbind删除双事件处理程序

$(".InputField").click(function()
{ 
    $('.FullBoxControl').show();
    $('.FullBoxControl').unbind();
    $('.FullBoxControl').click(function()
    {
        alert('Greetings');
    });
});

小提琴

设置一个标志来查看你是否已经添加了点击事件:

http://jsfiddle.net/x85A6/6/

var eventAttached = false;
$(".InputField").click(function() {
    if (!eventAttached) {
        $('.FullBoxControl').show();
        $('.FullBoxControl').click(function(){
            alert('Greetings');
        });
        eventAttached = true;
    }
});
$(".InputField2").click(function() {
    if (!eventAttached) {
        $('.FullBoxControl').show();
        $('.FullBoxControl').click(function(){
            alert('Greetings');
        });
        eventAttached = true;
    }
});
$(".InputField3").click(function() {
     if (!eventAttached) {
        $('.FullBoxControl').show();
        $('.FullBoxControl').click(function(){
            alert('Greetings');
        });
        eventAttached = true;
    }
});