【问题标题】:Access JS object inside jquery each() iterator function访问 jquery each() 迭代器函数中的 JS 对象
【发布时间】:2012-07-10 14:54:02
【问题描述】:
$('input.ISSelectSearch').each(function(i) {
    var box = new Object;
    box.size = 80;
    box.width = 110;
    //CODE CODE CODE
});

如何访问在上一次迭代中设置的box 的值?或者,是否可以通过某种密钥访问它?

$('input.ISSelectSearch').each(function(i) {
    var box = new Object;
    box.size = 80;
    box.width = 110;
    prevsize = $(this).box[/* previous iteration element id or name */].size
    //CODE CODE CODE
}); 

问题是我需要知道与每个'input.ISSelectSearch' 元素框相关联的数据,以便我可以根据当前或前一个框对象的值来更改它们。换句话说,我需要元素框对象之间的连接,以便我可以根据另一个对象的值指定其中的某些更改。

【问题讨论】:

    标签: javascript jquery javascript-objects


    【解决方案1】:

    你可以这样做

    var pre = null;
    $('input.ISSelectSearch').each(function(i) {
        var box = new Object;
        box.size = 80;
        box.width = 110;
        //condition so that first time it dosent shows an error
        if(pre!=null){
         //CODE
    
        }
        pre = this;
        //CODE CODE CODE
    }); 
    

    评论后编辑:-
    可能你想使用 $.data() 方法
    这是您可以将数据与元素相关联
    所以在循环内你可以做

    $('input.ISSelectSearch').each(function(i) {
        var box = new Object;
        box.size = 80;
        box.width = 110;
        $('input.ISSelectSearch').data(i,box);
        //and now you can retrive the data whenevr you want
        var olderObject = $('input.ISSelectSearch').data(SOME_OLDER_INDEX)
    });
    

    【讨论】:

    • 你确定你想要条件 pre!=null 吗?在哪个迭代中它不会为空?
    • 我猜你想要在 if 之外的 pre=this
    • 好的,如果我在每个循环中有 5 个元素,例如我需要从第 3 个元素访问第 1 个元素框对象属性。我不想使用任何全局变量,例如 pre。也许有一些操作方法可以访问内存中所有存储的盒子对象。我认为 JS 和 jquery 以某种方式将它们存储到内存或等共享存储中
    【解决方案2】:

    如果你喜欢,你可以用索引来做

    var $This = $('input.ISSelectSearch');
    $This.each(function (index, value) {
      var Pre;
      var box = { size: 80, width: 110 };
      if (index > 0) {
        Pre = $This[index - 1];
        //Your code hear
      } else {
        //otherwise
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2011-09-12
      • 1970-01-01
      • 2015-10-27
      • 2018-07-15
      • 2010-12-14
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多