Question

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?

Was it helpful?

Solution

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..

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top