Bind function to the event “onclick” of the elemen

2019-08-05 17:58发布

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

3条回答
看我几分像从前
2楼-- · 2019-08-05 18:15

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/

查看更多
神经病院院长
3楼-- · 2019-08-05 18:15

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

查看更多
三岁会撩人
4楼-- · 2019-08-05 18:26
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) });
}
查看更多
登录 后发表回答