【问题标题】:How to access HTML element's attributes in jQuery click event如何在 jQuery click 事件中访问 HTML 元素的属性
【发布时间】:2014-04-29 22:43:48
【问题描述】:

我正在使用 jQuery 生成按钮:

var button_a = $("<button />", {
                        text: 'A',
                        click: do_something,
                        class: "button a"
               });

var button_b = $("<button />", {
                        text: 'B',
                        click: do_something,
                        class: "button B"
               });

function do_something(){
    alert("Button Was pressed");
}

我想让do_something 改为这样做:

function do_something(name){
    alert("Button " + name + " was pressed");
}

如何更改 jQuery 按钮的创建,以便将 name 传递给 click: do_something

是事先创建闭包的唯一解决方案吗?

【问题讨论】:

    标签: javascript html jquery click closures


    【解决方案1】:

    确实 this 指的是您创建的按钮,但这需要事先在 DOM 元素上显示所有内容。

    如果您想了解更多信息,关闭会是更好的解决方案:

    (function ($) {
        var name = 'foo',
            someOtherData = { foo: 'bar' },
            button = $('<button>', {
                'text': 'yaay',
                'click': function () {
                    // i can use name, button in here
                }
            );
    }(jQuery));
    

    当然,可以使用可以传递给按钮的参数来重写自执行函数。这完全取决于点击时您需要多少信息。

    【讨论】:

      【解决方案2】:

      您可以在创建按钮时简单地提供nameid 属性并在其中访问它

      dosomething() 使用this 关键字,喜欢

      function do_something(){
        alert("Button"+ this.id+ " is pressed")
      }
      

      这里,this 指的是被点击的按钮..

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-08
        • 2018-06-08
        • 2016-10-26
        • 1970-01-01
        • 2014-10-30
        • 1970-01-01
        • 1970-01-01
        • 2019-01-06
        相关资源
        最近更新 更多