[英]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');
});
});
问我是否有人没有得到它。
使用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事件:
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.