簡體   English   中英

單擊內部單擊功能導致多次顯示警報消息 - Jquery / Javascript

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

我的問題很難解釋,所以我做了一個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

問我是否有人沒有得到它。

使用unbind刪除double事件處理程序

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

小提琴

請參考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');
    });
}

設置一個標志以查看您是否已附加click事件:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM