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

时间:2017-04-11 10:34:18

标签: 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);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
&#13;
&#13;
&#13;

jsFiddle Link

2 个答案:

答案 0 :(得分:1)

您编写仅适用于一次click事件的代码的方式不会更新文本,因为它已放入DOM中。因为你有一个变量foo,它有对象的引用。

然而,您需要与DOM交谈以更新其文本内容。我提到的一种方式。虽然你可能想要不引人注目。

您必须将this传递给函数:

onclick="second(this)" 

现在在函数中:

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

您可以使用委派事件在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>

答案 1 :(得分:0)

我不确定你想做什么。

这是我为句柄切换值

做的一个例子

click here to watch

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

 var select = 0;
  var text = $("#text");

  var handleSwitch = function(){
  if (select === 0){
    $(text).html(Json.content[1].title);
    select = 1;
  }else if(select === 1){
     $(text).html(Json.content[0].title);
     select = 0;
  }
 }

 $('#button').on("click", function(event){
    handleSwitch();
 });

<div class="container">
  <button id="button">click</button>
  <p id="text">Test 1</p>
</div>