序言:我是意大利人,对不起,我的英语不好。
这是我的问题:
我想为一组按钮分配一个功能。
我需要向函数发送一个参数。
这是我尝试过的代码:
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 #<HTMLButtonElement> has no method 'onClick'
你能告诉我哪里出错了,我该如何解决吗?
编辑:我需要迭代,因为我需要按钮的 'id 作为函数的参数,所以我需要做buttons[i].onClick(sayHello(buttons[i].id))
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
这不适用于您的示例:您有其他迭代原因吗?
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/
所以基于你的笔记:此标记和代码:
<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/