On和Live在动态添加元素时表现不同

时间:2012-09-17 11:13:57

标签: html jquery-plugins jquery jquery-on

我有以下代码,我尝试使用jQuery live和on plugin,在尝试使用live时,我能够添加事件处理程序,该处理程序已经为具有类“button”的元素提供给新添加的元素(在页面加载后动态添加)使用类“按钮”但是在尝试使用插件上的jQuery时,我无法将已存在的事件处理程序添加到新添加的元素中。

实时

示例
<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 ready之外的实时处理程序绑定代码,这正常工作但如果我在jquery ready之外使用事件处理程序绑定,则事件处理程序无法正常工作。提前感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

如果要对选择器进行动态测试,则必须将其作为参数传递,就像在代码中调用常量空集合中的函数一样:

jQuery(document).ready(function(){
   var i=0;
   function test(event){
      var elem=jQuery(this).parent().html();
      jQuery("body").append("<div class=DivClass" + i++ +   ">"+elem+"</div>" );
    } 
   $(document).on("click", ".button", test);
});

(在我将其传递给函数之前,你会看到我在这里定义test,你的代码会伤害我的眼睛)

答案 1 :(得分:0)

jQuery('body').on('click', '.button', test);
相关问题