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

查看:257
本文介绍了点击事件不会在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> 

委托事件的优点是可以处理事件后期添加到文档中的元素。


在创建元素时。



您需要使用 事件代表团 。您必须使用委托事件方法使用 .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屋!

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