문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top