1

it is based on jQuery Easy UI

Assume that here is the HTML code

<div id="menu" class="easyui-menu" style="width:120px;">
    <div>New</div>
    <div>
        <span>Open</span>
        <div style="width:150px;">
            <div><b>Word</b></div>
            <div>Excel</div>
            <div>PowerPoint</div>
        </div>
    </div>
    <div data-options="iconCls:'icon-save'">Save</div>
    <div class="menu-sep"></div>
    <div>Exit</div>
</div>

The problem is if you setup the menu in the loop, the function always triggered by the last statement, i.e. i always equals to 4 in console.log(itemLabel + i + "is selected.");

$(function(){
  var jqMenu = $("#menu");
  for (var i = 0; i < 5; i++) {
    var itemLabel = "item " + i;
    // correct
    var onclickFunction = function(){
        console.log(itemLabel + i + "is selected.");
    }

    jqMenu.menu("appendItem",{
      "text":itemLabel, 
      "onclick": function(){
        console.log(itemLabel + " is selected."); 
      } 
    });
  }
})
$(document).bind('contextmenu',function(e){
                e.preventDefault();
  $("#menu").menu('show', {
      left: 200,
      top: 100
  });
});
Weijing Lin
  • 575
  • 2
  • 5
  • 16

2 Answers2

0

the problem you are facing above can be solved using closures. I had this challenge once and solved it using closures.

Change your code to match this. Try using this format in your code.

for (var i = 0; i < 5; i++) {
    (function(x){
        console.log(x);
    })(i);
}
Edwin Kato
  • 543
  • 3
  • 11
0

Yeah, use a function to create a closure would help, also check out this answer: https://stackoverflow.com/a/3572616/883571

Personally I would suggest using forEach to bypass the problem:

[1,2,3,4,5].forEach(function(i) {
  console.log(i)
});
Community
  • 1
  • 1
jiyinyiyong
  • 4,586
  • 7
  • 45
  • 88