每个循环中的forEach函数mouseup

时间:2015-09-23 16:13:33

标签: javascript jquery

我有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事件。

3 个答案:

答案 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)

以下是其中一种方式:

&#13;
&#13;
//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;
&#13;
&#13;