【发布时间】:2012-09-17 11:13:56
【问题描述】:
我有以下代码,我尝试使用 jQuery live 和插件,在尝试使用 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 就绪之外使用 live 放置事件处理程序绑定代码,这工作正常,但如果我在 jquery 就绪之外使用事件处理程序绑定,则事件处理程序不起作用。提前感谢任何帮助。
【问题讨论】:
-
你可能应该使用delegate(); on() 仅当您调用该代码时页面上存在该元素时才有效。
-
.live()已被弃用,您应该查看.on() 不同版本的文档及其用法。
标签: html jquery-plugins jquery jquery-on