Bind function to the event “onclick” of the elements of an array of buttons

那年仲夏 提交于 2019-12-11 11:46:01

问题


Preamble: I'm Italian, sorry for my bad English.

This is my problem:

I want to assign a function to a set of buttons.

I need to send a parameter to the function.

this is the code that I've tried:

function test(atxt) {
    var buttons = $('.tblButton');

    for (var i = 0; i < buttons.length; i++) {
        buttons[i].onClick(sayHello(atxt));
    }
}

function sayHello(txt){alert('hello' + txt)};

...getting the following error:

Uncaught TypeError: Object #<HTMLButtonElement> has no method 'onClick'

can you tell me where I went wrong and how can I fix it?

EDIT: I need iteration because I need the 'id of the button as a parameter of the function so i need to do buttons[i].onClick(sayHello(buttons[i].id))


回答1:


Would this not work for your example: Do you have another reason for the iteration?

function test(atxt) {
    $('.tblButton').on('click',function(){sayHello(atxt);});
}

function sayHello(txt){alert('hello' + txt)};

OR optionally if the elements are static and present:

function test(atxt) {
    $('.tblButton').click(function(){sayHello(atxt);});
}

function sayHello(txt){alert('hello' + txt)};

Alternate approach: just change to this style:

var txt = "fred";
var atext = "hello" + txt;

function sayHello(atext) {
    alert(atext);
}
$('.tblButton').on('click', function() {
    sayHello(atext);
});
//below here just to demonstrate
$('.tblButton').eq(0).click();//fires with the fred
txt = "Johnny";// new text
atext = 'hello' + txt;
$('.tblButton').eq(1).click();//fires the Johnny

see it working here: http://jsfiddle.net/dFBMm/

SO based on your note: this markup and code:

<button class="tblButton" id="Ruth">Hi</button>
<button class="tblButton" id="Betty">Hi again</button>

$('.tblButton').on('click', function() {
    alert("Hello "+$(this).attr("id"));
});
$('.tblButton').eq(0).click();//fires with the Ruth
$('.tblButton').eq(1).click();//fires the Betty

http://jsfiddle.net/dFBMm/1/




回答2:


buttons[i].onClick(sayHello(atxt));

Supposed to be

$(buttons[i]).on('click', function() { sayHello(atxt) });

If you want to get the current button id then I think you are looking for this..

for (var i = 0; i < buttons.length; i++) {
     $(buttons[i]).on('click', function() { sayHello(this.id) });
}



回答3:


If you want to iterate through all of the buttons then you have to do that with .each() handler of the jquery:

$(function(){
  $(".tblButton").each(function () {
    $(this).click(function(){
       alert($(this).attr('id'));
    }); 
  });
});

checkout the jsbin: http://jsbin.com/usideg/1/edit



来源:https://stackoverflow.com/questions/13883225/bind-function-to-the-event-onclick-of-the-elements-of-an-array-of-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!