单击事件不会在 jquery 中触发 [英] Click event doesn't fire in jquery

查看:30
本文介绍了单击事件不会在 jquery 中触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

在您创建元素时.

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

一般语法

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

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

Ideally you should replace document with closest static container.

示例

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

这篇关于单击事件不会在 jquery 中触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆