将函数绑定到按钮数组元素的事件“onclick”
序言:我是意大利人,抱歉我的英语不好。
这是我的问题:
我想为一组按钮分配一个function。
我需要向函数发送一个参数。
这是我尝试过的代码:
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)};
…收到以下错误:
Uncaught TypeError: Object # has no method 'onClick'
你能告诉我哪里出错了,我该怎么办呢?
编辑:我需要迭代,因为我需要’按钮的id作为函数的参数,所以我需要做buttons[i].onClick(sayHello(buttons[i].id))
这不适用于您的示例:您是否有其他原因进行迭代?
function test(atxt) { $('.tblButton').on('click',function(){sayHello(atxt);}); } function sayHello(txt){alert('hello' + txt)};
或者,如果元素是静态的并且存在,则可选:
function test(atxt) { $('.tblButton').click(function(){sayHello(atxt);}); } function sayHello(txt){alert('hello' + txt)};
替代方法:只需改为这种风格:
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
看到它在这里工作: http : //jsfiddle.net/dFBMm/
所以基于你的笔记:这个标记和代码:
$('.tblButton').on('click', function() { alert("Hello "+$(this).attr("id")); }); $('.tblButton').eq(0).click();//fires with the Ruth $('.tblButton').eq(1).click();//fires the Betty
buttons[i].onClick(sayHello(atxt));
应该是
$(buttons[i]).on('click', function() { sayHello(atxt) });
如果你想获得当前的按钮ID,那么我认为你正在寻找这个..
for (var i = 0; i < buttons.length; i++) { $(buttons[i]).on('click', function() { sayHello(this.id) }); }
如果你想遍历所有按钮,那么你必须使用jquery的.each()
处理程序:
$(function(){ $(".tblButton").each(function () { $(this).click(function(){ alert($(this).attr('id')); }); }); });
结帐jsbin: http ://jsbin.com/usideg/1/edit