通过jQuery具有属性的动态按钮 [英] Dynamic buttons with attributes through jquery

查看:112
本文介绍了通过jQuery具有属性的动态按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我可以生成一个具有以下形式的代码的按钮

Alright, I can generate a button with code of the form

var temp = "<button type=\"button\" class=\"dynBtn\" id=\"anID\">Here!</button>";
$('#myDiv').append(temp).click(function(){
    window.alert("Hello! My id is " + this.id);
});

然后在运行时这实际上并没有工作,因为我得到的答案是id为"myDiv".另一方面,我也尝试使用以下方法:

And then on runtime this is not really working since I get as an answer for the id to be "myDiv". On the other hand, I also tried to use something like this:

$('#myDiv').append(temp).click(dynButtonClicked(this));

其中dynButtonClicked分别定义为

where dynButtonClicked is defined separately as

function dynButtonClicked (aButton) {
    window.alert("Hey, my id is " + aButton.id);    
};

但是,通过这种方式,在加载页面时单击了按钮,ID为未定义",此外,无论我单击按钮多少次,都不会收到其他警报(除了在页面正在加载).那么,我该怎么做呢?

However, this way, the button is clicked when the page is loaded, the id is 'undefined' and moreover, no matter how many times I click the button I get no further alerts (apart from the one I got while the page was loading). So, how can I do this right?

我想理想情况下,我想为运行时生成的所有按钮的类命名,然后单击其中的任何按钮以在

I guess ideally I would like to give a name for the class of all the buttons that are generated on runtime and then when clicking any of those to handle them somewhere in the

$(document).ready(...)

功能.但请继续,告诉我您的想法.实际上,稍后,我可能希望通过交互来删除按钮或禁用它们.因此,我正在寻找功能强大的产品.预先感谢您的宝贵时间.

function. But please, go ahead and tell me your thoughts. In fact, later on, through interaction I may want to delete the buttons or disable them. So, I am looking for something robust. Thank you in advance for your time.

推荐答案

以下是使用jQuery方式的方法:

Here's how to do it the jQuery way:

var $button = $('<button/>', {
  type: 'button',
  'class': 'dynBtn',
  id: 'anID',
  text: 'Here!',
  click: function() {
    window.alert('Hello! My id is '+ this.id);
  }
});

$button.appendTo('#myDiv');

这篇关于通过jQuery具有属性的动态按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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