【问题标题】:javascript passing variables from a method with a loop to a click functionjavascript将变量从带有循环的方法传递到点击函数
【发布时间】:2010-10-04 19:07:10
【问题描述】:

基本上,我试图传递一个在 JSON 数组中定义的变量,该数组在 for 循环中解析,以便在 click 语句中访问。

$(document).ready(function() {
  getJSON();
  var usedID;
 });
 function readJSON() {
  for (var i = 0; i < json.array.length; i ++) {
  usedID = json.array[i].id;
  var template = $('repeaterTemplate').clone();
  template.removeAttr('id');
  template.attr('id', 'k' + json.array.id);
  var omega = json.array.id;        
  $('#repeater').append(template);
  (function(o) {
     $('#' + o).click(function() {
    // this is where the submitID click function is now. It passes the omega value in

  });
  })(omega);

 }
 }
 $('.submitID').click(function() {
    submitNow(usedID);
  }

现在我的 for 循环中有 submitID click 函数,它导致 submitNOW 函数被调用,但循环循环多次。谁能帮我将用户 ID 从 readJSON() 传递给 click 函数?

我的每个函数都出现解析错误:

var userID = [];
var j = 0;
$('.submitNOW').each(function() {
   function(id) {
$(this).click(function() {
  submitNow(id);
});
  }(userID[j]);
});

【问题讨论】:

  • 所以您希望每个.submitID 元素以不同的userID 值调用submitNow?还是所有这些值都相同?
  • 您可能想研究使用 jQuery 的 'each' 方法来迭代数据,它会减少一些循环样板。
  • 您在 for 循环中获得了 usedID 值。因此,预计会有多个 ID。你想通过哪一个?
  • -lincolnk,是的,我需要不同的用户 ID 值。对特定列表项进行点击操作时选择正确的值
  • @sandeepan 这是一种自调用方法——它被定义,然后以omega 作为参数立即调用。它用于保存循环内变量的值。

标签: javascript jquery scope


【解决方案1】:

我认为您正在尝试执行此类操作,但您无法将特定用户 ID 与特定元素相关联。

此示例按照遇到的顺序将用户 ID 提供给 .submitID 元素。它还假设用户 ID 和元素的数量相同。

/* this is a non-working example */

var usedIDs = [];

function readJSON() {
    for (var i = 0; i < json.array.length; i++) {
        usedIDs.push(json.array[i].id);
        moreFunctions();
        moreStuff();
    }
}

var j = 0;

$('.submitID').each(function () {

    function (id) {
        $(this).click(function () {
            submitNow(id);
        });
    }(usedIDs[j]);

    j++;

});

编辑:根据您的帖子修订,这是我对您尝试做的最好的猜测。

function readJSON() {

    for (var i = 0; i < json.array.length; i++) {

        var usedID = json.array[i].id;

        var template = $('repeaterTemplate').clone();
        template.removeAttr('id');
        template.attr('id', 'k' + usedID);
        $('#repeater').append(template);

        (function (o) {
            // assumign template is a jQuery object here; if not use $(template) instead
            template.click(function () {
                // this is where the submitID click function is now. It passes the omega value in 
                submitNow(o);
            });
        })(usedID);

    }
}

【讨论】:

  • 嘿,看看我的代码示例。我的每个函数的示例都出现解析错误
  • @fordays 在(userID[j]); 之前缺少) 保持冷静! :)
猜你喜欢
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多