jQuery-动态创建按钮并附加事件处理程序 [英] jQuery - Dynamically Create Button and Attach Event Handler

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

问题描述

我想使用jQuery向表中动态添加按钮控件,并附加一个click事件处理程序.我尝试了以下方法,但没有成功:

I would like to dynamically add a button control to a table using jQuery and attach a click event handler. I tried the following, without success:

$("#myButton").click(function () {
    var test = $('<button>Test</button>').click(function () {
        alert('hi');
    });

    $("#nodeAttributeHeader").attr('style', 'display: table-row;');
    $("#addNodeTable tr:last").before('<tr><td>' + test.html() + '</td></tr>');
});

上面的代码成功添加了新行,但是不能正确添加按钮.我将如何使用jQuery完成此操作?

The above code successfully adds a new row, but it doesn't handle adding the button correctly. How would I accomplish this using jQuery?

推荐答案

调用.html()会将元素序列化为字符串,因此所有事件处理程序和其他关联数据都将丢失.这是我的处理方式:

Calling .html() serializes the element to a string, so all event handlers and other associated data is lost. Here's how I'd do it:

$("#myButton").click(function ()
{
    var test = $('<button/>',
    {
        text: 'Test',
        click: function () { alert('hi'); }
    });

    var parent = $('<tr><td></td></tr>').children().append(test).end();

    $("#addNodeTable tr:last").before(parent);
});

或者,

$("#myButton").click(function ()
{    
    var test = $('<button/>',
    {
        text: 'Test',
        click: function () { alert('hi'); }
    }).wrap('<tr><td></td></tr>').closest('tr');

    $("#addNodeTable tr:last").before(test);
});

如果您不喜欢将属性映射传递给$(),则可以改用

If you don't like passing a map of properties to $(), you can instead use

$('<button/>')
    .text('Test')
    .click(function () { alert('hi'); });

// or

$('<button>Test</button>').click(function () { alert('hi'); });

这篇关于jQuery-动态创建按钮并附加事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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