单击内部单击功能导致多次显示警报消息 - Jquery / Javascript

时间:2014-05-09 16:05:07

标签: javascript jquery html css

我的问题很难解释,所以我做了jsfiddle。问题是。当我第一次点击<li>时,我收到1条提醒信息。

现在我再次点击任何<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

问我是否有人没有得到它。

3 个答案:

答案 0 :(得分:1)

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

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

Fiddle

答案 1 :(得分:1)

参考jsfiddle。每次单击输入字段时,它都会绑定click事件,因此在重新绑定click事件之前,有必要将重复代码放在常用函数中并取消绑定click事件。

$(".InputField").click(function()
{
    fullbox();
});

$(".InputField2").click(function()
{
    fullbox();
});

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

答案 2 :(得分:0)

设置标志以查看您是否已附加点击事件:

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;
    }
});