如何正确绑定(bind)值j
在下面的例子中?
for (j = 0; j < shorts[i+1].length; j++) {
$('#Container').append($('<button id="but'+(j+1)+'" type="button" onclick="func(this,j)">'+ values[j]+'</button>'));
)};
最佳答案
j
应作为变量连接起来,否则它将被视为字符串,并且 onclick 方法将类似于 func(this,j)
。
这应该可以实现onclick="func(this,'+j+')"
for (j = 0; j < shorts[i+1].length; j++) {
$('#Container').append($('<button id="but'+(j+1)+'" type="button" onclick="func(this,'+j+')">'+ values[j]+'</button>'));
};
<小时/>
选项 2
您还可以通过像这样的绑定(bind)而不是内联 onclick 方法来实现
var $button = $('<button />')
.attr('id', j+1)
.text(j+1)
.on('click', func.bind(null, j+1));
$('#Container').append($button);
这样,函数就可以使用值 j+1。
function func(a){
alert(a);
}
for (var j = 0; j < 10; j++) {
var $button = $('<button />')
.attr('id', j+1)
.text(j+1)
.on('click', func.bind(null, j+1));
$('body').append($button);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
关于javascript - 将循环索引与函数参数绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30718942/