点击事件不会在jquery中触发

时间:2015-02-01 08:08:37

标签: javascript jquery html

我添加了一个新元素但是当我点击它时它没有响应。

HTML

<button>add element</button>
<div></div>

的Javascript

$(function(){
    $('button').click(function(){
        $('div').append('<span class="x">x</span>');
    });

    $('.x').click(function(){
        alert('fire'); 
        });
});

4 个答案:

答案 0 :(得分:7)

&#13;
&#13;
$(function() {
  $('button').click(function() {
    $('div').append('<span class="x">x</span>');
  });

  $('div').on('click', '.x', function() {
    alert('fire');
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>add element</button>
<div></div>
&#13;
&#13;
&#13;

事件处理程序仅绑定到当前选定的元素;它们必须存在于您的代码进行事件绑定调用时的页面上。

  

委托事件的优势在于它们可以处理来自稍后添加到文档的后代元素的事件。

在创建元素时。

您需要使用Event Delegation。您必须使用委托事件方法来使用.on()

一般语法

$(document).on(event, selector, eventHandler);

理想情况下,您应该将document替换为最近的静态容器。

实施例

$('div').on('click', '.x', function(){
    alert('fire'); 
});

答案 1 :(得分:4)

当文档中不存在该元素时,无法通过调用$(".x")将点击事件绑定到动态生成的元素。 其中一个解决方案是使用事件委派,类似于

$(document).on("click",".x",function(){
// do your work here
})

另一种方法是在生成元素时将click事件绑定到元素

$('button').click(function(){
    $('div').append($("<span>",{
          class: x
    }).text("x").click(function(){
          // do your work here
    }));
});

答案 2 :(得分:1)

您在x类存在的项目之前添加事件侦听器。您希望在追加该范围后立即添加该事件侦听器。

$(function(){
    $('button').click(function(){
        $('div').append('<span class="x">x</span>');
        $('.x').click(function(){
            alert('fire'); 
        });
    });

});

答案 3 :(得分:1)

您无法将事件直接绑定到jQuery中动态创建的元素。

使用event-delegation绑定到动态创建的元素的父级:

$(function(){
    $('button').click(function(){
        $('div').append('<span class="x">x</span>');
    });

    $('button').on("click", ".x", (function(){
        alert('fire'); 
        });
});

有关详细信息,请参阅:http://api.jquery.com/on/