我有foreach循环:
objects.forEach(function(object) {
var button = '<tr><td>' + object.object.code + '</td><td>' +
formatDistance(1456000) + '</td></tr>';
$(button).mouseup(function(event) {
if (event.which == 1) {
runObject(object);
}
});
result += button;
});
$(mydiv).html(result);
但这不起作用。我只在每个forEach
周期中列出了一个对象。
如何为每个循环点正确编写onclick
事件。
答案 0 :(得分:0)
您可以将每个项目附加到div
循环内的forEach
:
objects.forEach(function(object) {
var button = $('<tr><td>' + object.object.code + '</td><td>' + formatDistance(1456000) + '</td></tr>');
button.mouseup(function(e) { if(e.which === 1) { runObject(object); } });
$(mydiv).append(button);
});
答案 1 :(得分:0)
试试这个
objects.forEach(function(object) {
var button = '<tr class="test_' + object.object.code + "'><td>' + object.object.code + '</td><td>' +
formatDistance(1456000) + '</td></tr>';
$('.test_' + object.object.code).mouseup(function(event) {
if (event.which == 1) {
runObject(object);
}
});
result += button;
});
$(mydiv).html(result);
你必须解决语法错误
答案 2 :(得分:0)
以下是其中一种方式:
//Create an empty container
var $result = $();
[1,2,3,4].forEach(function(object) {
//Create TRs as jQuery objects (as opposed to strings), append whatever
var $button = $('<tr/>').append('<td>[' + object + ']: </td><td>' + ("this is " + object) + '</td>');
//Bing events, mouseup, click or whatever
$button.on("mouseup", function(e) {
//Add whatever conditions you like
if (e.which === 1) {
alert (object);
}
});
//Keep adding the TR to the container
$result = $result.add($button)
});
//Append all at once, outside the loop
$("#mydiv").empty().append($result);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv"></div>
&#13;