jQuery:如何给动态生成的元素绑定事件?

jQuery的html()能够给如今元素附加新的元素,innerHTML也能够,那么,如何给这些新生成的元素绑定事件呢?直接在元素还未生成前就绑定确定是无效的,由于所绑定的元素目前根本不存在。javascript

然而,jQuery为咱们提供了一个函数来解决这个问题,它就是.live()(备注:jquery的后期版本变为.on() ),它能够给全部元素绑定事件,不管是已有的,仍是未来生成的,好比:html

$(‘#div’).live(‘click’,function(){ 
    //do stuff 
}); 

它还能够同时绑定多个事件:
$('.hoverme').live('mouseover mouseout', function(event) {
  if (event.type == 'mouseover') {
    // do something on mouseover
  } else {
    // do something on mouseout
  }
});

【实例】java

<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js">
</script>
<html>
    <body>
        <input type="button" name="input[]" value="按钮1" />
        <input type="button" name="input[]" value="按钮2" />
        <input type="button" name="input[]" value="按钮3" />
        <a id="add">添加</a>
    </body>
</html>
<script type="text/javascript">
    $("#add").click(function() {
        var inp = $(":input:last").clone();
        $(":input:last").after(inp);
    })

    // 为每个button绑定onclick事件,alert一下
    var inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) {
        inputs[i].onclick = function() {
            alert("我测试一下");
        }
    }

    $(':input').live('click',function() {
        alert("我再测");
    });
</script>

<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js">
</script>
<html>
    <body>
        <input type="button" name="input[]" value="按钮1" />
        <input type="button" name="input[]" value="按钮2" />
        <input type="button" name="input[]" value="按钮3" />
        <a id="add">添加</a>
    </body>
</html>
<script type="text/javascript">
    $("#add").click(function() {
        var inp = $(":input:last").clone();
		inp2 = inp.val("按钮"+($(":input").length+1));
		inp3 = inp2.attr("id","a"+($(":input").length+1))
        $(":input:last").after(inp3);
    })

    //为每个button绑定onclick事件,alert一下
    //var inputs = document.getElementsByTagName("input");
	//预先加载,inputs.length最大等于3
    for (var i = 0; i < 99; i++) {
		$("#a"+i).live('click',function(){
			alert($(this).val());
		})
    }
	
    $(':input').live('click',function() {  
        alert($(this).val());
    });	
</script>
相关文章
相关标签/搜索