jQuery工具提示在循环中设置动态内容返回最后一个值

时间:2017-11-26 21:26:51

标签: javascript jquery jquery-ui-tooltip

变量intcontent对于所有工具提示元素始终是相同的值。如何将正确的值传递给工具提示内容函数?

for(var x=0; x<arr_dj[i].style.length; x++){
  if(x != 0)$divstyle.append($('<span> / </span>'));
    var $span = $('<span></span>');
    $span.append(getconststr(arr_dj[i].style[x]));
    var intcontent = arr_dj[i].style[x];
    $span.tooltip({
      items: "div",
      tooltipClass: "style_tooltips",
      position: {
        my: "left-25 top", 
        at: "right bottom "
      },
      content: function(e) {
        var html = getmusicdef(intcontent);
        return html;
      }
    });
    $divstyle.append($span);
  }
}

1 个答案:

答案 0 :(得分:1)

变量intcontentcontent函数中可用作闭包,但是在执行该函数时,它被设置为最后一个值。使用IIFE将其设置为每次迭代的正确值:

for(var x=0; x<arr_dj[i].style.length; x++){
  if(x != 0){//not sure what you wanted to do here, posted code has too many }
    $divstyle.append($('<span> / </span>'));
    var $span = $('<span></span>');
    $span.append(getconststr(arr_dj[i].style[x]));
    var intcontent = arr_dj[i].style[x];
    $span.tooltip({
      items: "div",
      tooltipClass: "style_tooltips",
      position: {
        my: "left-25 top", 
        at: "right bottom "
      },
      content: (function(intcontent){
        return function(e) {
          var html = getmusicdef(intcontent);
          return html;
        }
      }(intcontent))//IIFE setting intcontent correctly
    });
    $divstyle.append($span);
  }
}