这对您的示例不起作用:您是否有其他迭代原因?
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/