dom元素新增后不会触发事件

<!DOCTYPE HTML>
<html>
<head>
<title>checkbox设置只能单选</title>
<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js">
</script>

</head>
<body>
<p>您喜欢的水果?</p>
<button id="add">新增</button>
<form>
    <div id="checkboxDiv" >
        <input type="checkbox" name="checkboxName" value="1" />苹果<br/>
        <input type="checkbox" name="checkboxName" value="2" />西瓜<br/>
        <input type="checkbox" name="checkboxName" value="3" />香蕉<br/>
        <input type="checkbox" name="checkboxName" value="4" />桃子<br/>
        <input type="checkbox" name="checkboxName" value="5" />芒果<br/>
    </div>
</form>
<script type="text/javascript">
$(document).ready(function(){

    $("#checkboxDiv").on("click", "input", function(){
        if($(this).is(':checked')){ 
            $(this).attr('checked',true).siblings().attr('checked',false);
        }else{
            $(this).attr('checked',false).siblings().attr('checked',false);
        }
    })

    $("#add").click(function(){
        $("#checkboxDiv").append("<input type='checkbox' name='checkboxName' value='6' />梨子<br/>");
    })
});

</script>
</body>
</html>

  新增的元素一定要在$("#父元素")内

posted @ 2019-08-29 17:59  yewook  阅读(311)  评论(0编辑  收藏  举报