【问题标题】:jQuery change variable and apply to previously ran codejQuery 更改变量并应用于以前运行的代码
【发布时间】:2016-12-28 02:00:30
【问题描述】:

我想浏览一个 JSON 文件。为了能够做到这一点,我创建了更改变量i 的值的导航链接。我缺少的是如何在上面的代码中应用变量更改。

$(document).ready(function(){
  var i = 0;
  var len = 10;
  $.getJSON(file, function(data) {
    $.each(data, function (id, dat) {           
      $('div').append('<p>'+ id +'<span id="nav'+ id +'">');
      for(var j = 0; j < Object.keys(dat).length; j += len){
        $('#nav'+ id).append('<a>'+ j +'</a> ');
      }
      $('div').append('</span></p>');
      $.each(dat, function (k, d) {
       if((k >= i) && (k < i + len)) $('div').append('<span>'+d.detail)+'</span>'; //change i
      });
    });
  });

  $('div').on('click', '[id^=nav] a', function(){
    i = $(this).text();
  });   
});

更新:这是 JSON 文件

{"5498":[{"detail":"ny"},{"detail":"qwe"},{"detail":"ghg"},{"detail":"werwe"},{"detail":"bgg"},{"detail":"qwe"},{"detail":"hgh"},{"detail":"qewq"},{"detail":"ggf"},{"detail":"vc"},{"detail":"htr"},{"detail":"htr"},{"detail":"jtyj"},{"detail":"eqw"},{"detail":"gfg"}],"46546":[{"detail":"greger"},{"detail":"jytjyt"},{"detail":"werwer"},{"detail":"jjyt"},{"detail":"greger"},{"detail":"hjtyjty"},{"detail":"fds"},{"detail":"thtr"},{"detail":"qwe"},{"detail":"htrh"},{"detail":"jyjjy"},{"detail":"ewrwe"}]}

脚本会产生这样的输出

54980 10 

nyqweghgwerwebggqwehghqewqggfvc

465460 10 

gregerjytjytwerwerjjytgregerhjtyjtyfdsthtrqwehtrh

我希望在单击某些链接时对其进行更改 e. G。单击“10”时,输出将如下所示。如果我点击“0”,它会再次像上面那样。

54980 *10*

htrhtrjtyjeqwgfg

465460 10 

gregerjytjytwerwerjjytgregerhjtyjtyfdsthtrqwehtrh

【问题讨论】:

  • 如果没有带有相关 JSON 的独立示例,很难说。您可以伪造 getJSON 并只提供 JSON。
  • 我添加了 JSON 文件
  • 这是您所期望的吗? jsfiddle.net/xx2w20er ?
  • 点击导航中的“10”链接后,我希望下面的数据会发生变化
  • 这里的“我”是什么? $('div').on('click', '[id^=nav] a', function(){ i = $(this).text(); }); 你在哪里展示它

标签: jquery variables onclick


【解决方案1】:

最好的解决方案似乎是在解析时创建一个对象/数组,然后修改内容

 $('div').on('click', '[id^=nav] a', function(){
   i = $(this).text()*1;
   for(var j = i; j < i + len; j ++) if(!(obj[id][j] === undefined || obj[id][j] === null)) $('#nav'+id).after('<span>'+obj[id][j].detail)+'</span>');
});   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    相关资源
    最近更新 更多