简体   繁体   中英

How to access HTML element's attributes in jQuery click event

I am generating buttons with jQuery using:

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");
}

I would like to make it so do_something instead do:

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

How could I change the jQuery button creation so that I could pass in a name to the click: do_something ?

Is the only solution to create a closure before hand?

You can simply give a name or id attribute while creating the button and access it in

dosomething() using this keyword, like

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

here, this will refer to the button that is clicked..

Indeed this refers to the button you have created but that would require everything to be present on the DOM element beforehand.

If you want more information a closure would be nicer solution:

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

Of course the self executing function can be rewritten with arguments which you can pass to your button. It all depends how much information you need when it's clicked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM