我有以下代码,我试着用jQuery live和plugin,在尝试使用live时,我能够添加已经存在的元素的事件处理程序类“按钮”添加到新添加的元素(在页面加载后动态添加)与类“按钮”,但尝试与插件上的jQuery,我无法将已经存在的事件处理程序添加到新添加的元素。On和Live对动态添加元素的行为有所不同
与现场
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<!--START: Adding of javaScript library -->
<script type="text/javascript" src="script/jquery.min.js"></script>
<!--END: Adding of javaScript library-->
<!--START: Adding of javaScript library need internet Connection-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<!--END: Adding of javaScript library need internet Connection-->
</head>
<script>
jQuery(document).ready(function(){
jQuery(".button").live("click", test);
});
var i=0;
function test(event){
var elem=jQuery(this).parent().html();
jQuery("body").append("<div class=DivClass" + i++ + ">"+elem+"</div>");
}
</script>
<body>
<div id="Container"><input value="click me" class="button" type="button"/></div>
</body>
</html>
示例在示例在
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<!--START: Adding of javaScript library -->
<script type="text/javascript" src="script/jquery.min.js"></script>
<!--END: Adding of javaScript library-->
<!--START: Adding of javaScript library need internet Connection-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<!--END: Adding of javaScript library need internet Connection-->
</head>
<script>
jQuery(document).ready(function(){
jQuery(".button").on("click", test);
});
var i=0;
function test(event){
var elem=jQuery(this).parent().html();
jQuery("body").append("<div class=DivClass" + i++ + ">"+elem+"</div>");
}
</script>
<body>
<div id="Container"><input value="click me" class="button" type="button"/></div>
</body>
</html>
而且我能够用活jQuery的准备这是工作的罚款之外把事件处理程序绑定代码,但如果我把事件处理程序绑定使用jQuery以外的准备,事件处理程序不起作用。提前感谢任何帮助。
你或许应该使用委托(); on()仅当您调用该代码时页面上存在该元素才有效。 – MassivePenguin
'.live()'已弃用,您应该查看不同版本的[.on()](http://api.jquery.com/on/)的文档以及那里的用法。 – Andreas