为使用jQuery动态创建的按钮添加点击事件 [英] Adding click event for a button created dynamically using jQuery

查看:84
本文介绍了为使用jQuery动态创建的按钮添加点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在使用jQuery动态添加的按钮上添加按钮单击事件?



div container:

  $('#pg_menu_content')。empty(); 
$ div = $('< div data-role =fieldcontain/>');
$(< input type ='button'value ='动态按钮'id ='btn_a'/>\").appendTo($div.clone()).appendTo('#pg_menu_content');

问题1:
如何添加点击事件为上面的按钮?我尝试了下面的内容,但没有触发

pre $ $ c $ $(#btn_a)。click(function(){
警报('点击按钮');
});

问题2:
如何获取点击事件中的按钮?例如,我想在click事件函数中获取'Dynamic Button'值。

您可以帮我解决这个问题。



  

使用一个绑定到容器的委托事件处理程序:

> $('#pg_menu_content')。on('click','#btn_a',function(){
console.log(this.value);
});

也就是说,绑定到JS运行时存在的元素(我假设 #pg_menu_content 在页面加载时存在),并在第二个参数中为 .on()提供一个选择器。当在 #pg_menu_content 元素上发生点击时,jQuery会检查它是否应用于与 #btn_a 匹配的元素的子元素。选择器。



或者在创建按钮后绑定标准(未委托的)点击处理程序。

无论哪种方式,在点击处理程序中,这个将引用有问题的按钮,所以 this.value 会给你它的价值。


How to add a button click event on a button that was added dynamically using jQuery?

The jQuery code that adds the dynamic buttons inside a div container:

$('#pg_menu_content').empty();
$div = $('<div data-role="fieldcontain"/>');
$("<input type='button' value='Dynamic Button' id='btn_a' />").appendTo($div.clone()).appendTo('#pg_menu_content');

Question 1: How can I add a click event for the above button? I tried the below and it has not triggered

$("#btn_a").click(function(){
  alert ('button clicked');
});

Question 2: How can I get the value of the button inside the click event? For example I want to get the value 'Dynamic Button' inside the click event function.

Can you guys please help me on this.

解决方案

Use a delegated event handler bound to the container:

$('#pg_menu_content').on('click', '#btn_a', function(){
    console.log(this.value);
});

That is, bind to an element that exists at the moment that the JS runs (I'm assuming #pg_menu_content exists when the page loads), and supply a selector in the second parameter to .on(). When a click occurs on #pg_menu_content element jQuery checks whether it applied to a child of that element which matches the #btn_a selector.

Either that or bind a standard (non-delegated) click handler after creating the button.

Either way, within the click handler this will refer to the button in question, so this.value will give you its value.

这篇关于为使用jQuery动态创建的按钮添加点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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