读书人

jquery 为啥 会触发两次事件

发布时间: 2013-04-02 12:35:26 作者: rapoo

jquery 为什么 会触发两次事件?

$(function(){
$("label").click(function(){
if($(this).children("input[name='checkbox']").attr("checked")=='checked'){
$(this).children('input').removeAttr("checked");
$("#"+$(this).children('input').val()).parent().remove();
}else{
$(this).children('input').attr("checked","checked");
$(this).parent().addClass("on");
$(".options").show();
var element='<li>'+$(this).attr("title")+'<a href="#" onclick="delCon(this)" id="'+$(this).children('input').val()+'" title="删除此条件"></a></li>';
$("#conditions").append('<li>'+$(this).attr("title")+'<a href="#" onclick="delCon(this)" id="'+$(this).children('input').val()+'" title="删除此条件"></a></li>');
}
//alert($("input:checked").length);
if($("input:checked").length>0){
$("#cover").css('display','block');
var conditions="";
var url='sub/getHotelList.php?v='+Math.random();
$("input:checked").each(function(data){
conditions+=$(this).val()+",";

});
$.post(url,{items:conditions},function(data){
//alert(data);
$("#hotellist").html(data);
$("#cover").css('display','none');
$("#content").html(data);
});
}
});
});

<dl class="fit">
<dt>星级</dt>
<dd><input type="checkbox" id="star5" name="checkbox" value="5" /><label for="star5" title="五星">五星</label></dd>
<dd><label for="star4" title="四星"><input type="checkbox" id="star4" name="checkbox" value="4" />四星</label></dd>
<dd><label title="三星"><input type="checkbox" name="checkbox" value="3" />三星</label></dd>
<dd><label title="经济"><input type="checkbox" name="checkbox" value="2" />经济</label></dd>
</dl>
<dl class="fit">
<dt>房价</dt>
<dd><label title="600元以上"><input type="radio" name="pfilter" value="1" title="600元以上" />600元以上</label></dd>
<dd><label title="300-600元"><input type="radio" name="pfilter" value="6" />300-600元</label></dd>
<dd><label title="150-300元"><input type="radio" name="pfilter" value="7" />150-300元</label></dd>
<dd><label title="150元以下"><input type="radio" name="pfilter" value="8" />150元以下</label></dd>
</dl>
点击以后会执行两次?求指教
[解决办法]
<dd><input type="checkbox" id="star5" name="checkbox" value="5" /><label for="star5" title="五星">五星</label></dd>应该是:<dd><label for="star5" title="五星"><input type="checkbox" id="star5" name="checkbox" value="5" />五星</label></dd>吧?
还有真看不懂你的目的。
至于执行两次原因是<label>与包含的<input>有联动关系,你可简单测试一下:
<label onclick="alert(0)"><input type="checkbox" name="tt" value="1" />点一下执行两次onclick</label>

[解决办法]
用alert进行一步步调试,看看那里是触发的。然后再排除,是否条件除了问题
------解决方案--------------------


应为input是包含在label里面的 input会触发一次 label也会触发一次 $("input").change(function(){})
[解决办法]
首先,你的dom结构很不好。<label>与<input>不是嵌套来使用的。
正确的用法是<label for="a">文字</label><input id="a" type="radio">
通过<label>的for属性让label与<input>绑定起来,作用是点击<label>中的文字,<input>也能选中。

建议修改一下。

读书人网 >JavaScript

热点推荐