2014-05-09 19 views
0

我的問題很難解釋,所以我做了一個jsfiddle。問題在於。當我第一次點擊<li>時,我收到1條警告消息。點擊裏面點擊功能導致警告消息顯示不止一次 - jquery/Javascript

現在我再次點擊任何<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> 

Script代碼:

$(".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

問我你是否有人不明白。

回答

1

請參閱jsfiddle。每次在輸入字段中單擊時,它會綁定單擊事件,因此在重新綁定單擊事件之前,需要將重複的代碼放入常用函數並解除綁定單擊事件。

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

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

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

即將發佈相同的東西。這可能是你最好的選擇 –

+0

@DylanCorriveau歡呼! – Dave

1

使用unbind刪除重複的事件處理程序

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

Fiddle

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