点击事件不会在jquery中触发 [英] Click event doesn't fire in jquery
问题描述
我附加了一个新元素,但是当我点击它时,它没有任何回应。
HTML
<按钮>添加元素< / button>
< div>< / div>
Javascript
$(function(){
$('button')。click(function(){
$('div')。append('< span class =x> ();
$ b $('。x')。click(function(){
alert('fire');
});
});
< script src =https://ajax.googleapis .com / ajax / libs / jquery / 2.1.1 / jquery.min.js>< / script><按钮>添加元素< / button>< div>< / div> $ c $事件处理程序仅绑定到当前选定的元素;而事件处理程序只绑定到当前选定的元素。它们必须在您的代码进行事件绑定调用时存在于页面中。
委托事件的优点是可以处理事件后期添加到文档中的元素。
在创建元素时。
您需要使用 事件代表团 。您必须使用委托事件方法使用 .on() 。
常规语法
$(document).on(event,选择器,eventHandler);
理想情况下,您应该将文档
替换为最接近的静态容器。
$ b 示例 $('div')。on('点击','.x',function(){
alert('fire');
});
I appended a new element but when I click on it it has no response.
HTML
<button>add element</button>
<div></div>
Javascript
$(function(){
$('button').click(function(){
$('div').append('<span class="x">x</span>');
});
$('.x').click(function(){
alert('fire');
});
});
解决方案
$(function() {
$('button').click(function() {
$('div').append('<span class="x">x</span>');
});
$('div').on('click', '.x', function() {
alert('fire');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>add element</button>
<div></div>
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
As you are creating elements.
You need to use Event Delegation. You have to use .on() using delegated-events approach.
General Syntax
$(document).on(event, selector, eventHandler);
Ideally you should replace document
with closest static container.
Example
$('div').on('click', '.x', function(){
alert('fire');
});
这篇关于点击事件不会在jquery中触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!