javascript - 单击时在 JSON 数组选项之间切换

标签 javascript json

我试图通过更改变量的值来单击按钮时在数组选项之间切换。我无法让它工作。也许这不是最好的方法?我仍在学习这一点,并且正在努力发现问题。

预先感谢您的帮助

var json = {
  "content": [{
      "title": "Test 1",
    },
    {
      "title": "Test 2",
    }
  ]
};

var output = ""; //initialize it outside the loop
var maxAppend = 0;

var foo = json.content[0];

function first() {
  foo = json.content[0];
}

function second() {
  foo = json.content[1];
}

$.each(json.content[0], function() {
  if (maxAppend >= 1) return;

  output += '<h2>' + foo.title + '</h2>' +
    '<div><button onclick="second()">click</button></div>'

  maxAppend++;

});

$('.container').append(output);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>

jsFiddle Link

最佳答案

您编写的代码只能运行一次,并且 click 事件不会更新文本,因为它已放入 DOM 中。因为你有一个变量 foo 并且它具有对该对象的引用。

但是您需要与 DOM 通信才能更新其文本内容。我提到的一种方法。尽管您可能想保持低调。

您必须将 this 传递给函数:

onclick="second(this)" 

现在在函数中:

function second(el){
  $(el).parent().prev('h2').text(json.content[1]['title']);
}

您可以使用委托(delegate)事件为 jquery 中的动态按钮添加事件监听器:

$(document.body).on('click', 'button' second);
function second(){
    $(this).parent().prev('h2').text(json.content[1]['title']);
}

var json = {
  "content": [{"title": "Test 1",},{"title": "Test 2",}]
};
var output = ""; //initialize it outside the loop
var maxAppend = 0;
var foo = json.content[0];

function first() {
  foo = json.content[0];
}
function second(el) {
  $(el).parent().prev('h2').text(json.content[1]['title']);
}

$.each(json.content, function() {
    output += '<h2>' + foo.title + '</h2>' +
    '<div><button onclick="second(this)">click</button></div>'
  maxAppend++;
});

$('.container').append(output);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>

关于javascript - 单击时在 JSON 数组选项之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43343523/

相关文章:

PHP file_get_contents 返回 false

Python:如何获取elasticsearch查询的总命中数

javascript - Google map 中心和信息窗口

javascript - 以相同的形式处理javascript和php中的下拉列表操作

javascript - Angular 2 - 使用 Angular-route 3.3.0 覆盖路线

javascript - 如何搜索和过滤大型数据集(JSON/AngularJS)

javascript - jQuery-根据多个条件计算百分比

ruby-on-rails - rails hash.as_json 方法产生带有 bool 值的意外结果

javascript - 通过 $ionicActionSheet.show() 在 ionic 中打开文件资源管理器

javascript - 通过表 html 触发 Backbone.js 事件