将json结果中的变量插入jQuery .on()单击处理程序

时间:2016-09-08 03:49:09

标签: jquery json loops

我在JSON对象中有一组联系人但是.on('click'...)事件中显示的变量始终是JSON数组中的最后一项。

<a> id设置正确但警报始终返回JSON数组中的最后一个contactID

我的代码中有什么东西是错误的吗?

  var theDIV = $('#1234DIV');
  for (var i=0;i<theJSON.contacts.length;i++) {
    var theContact = theJSON.contacts[i];
    var contactID = theContact.contact_id;

    var theLink = $('<a>',{
      'id': 'Acontact_'+contactID,
      'href':'javascript:;',
    }).on('click', function(event) {
      console.log(event);
      console.log(contactID);
      alert(contactID);
    }).html(theContact.name_display);

    theDIV.append(theLink);
  }

以下是JSON示例:

 {"result_count":2,"contacts":[{"contact_id":"508","name_display":"George Washington","flag_type":"contact","name_title":"","name_first":"George","name_last":"Washington"},"contact_id":"716","name_display":"Red","flag_type":"contact","name_title":"","name_first":"Red","name_last":"Shawshank"}]}

2 个答案:

答案 0 :(得分:0)

嘿Tim,您在循环的每次迭代中都会覆盖contactID的值,因此只有一个&#34; contactID&#34;这将是你json中的最后一个。

有几件事。

您不需要在生成的每个新<a>代码上附加单独的点击操作。为每个人指定一个特定的类名,例如"button",然后使用

$('body').on('click', '.button', function (){
        alert( $(this).data("contactID") );
});

通过将其附加到正文,它将捕获所有新创建的a.button元素。

然后在你的循环中做

var theLink = $("<a>", {
    'id': 'Acontact_'+contactID, 
    'class': "button"
}).html(theContact.name_display).data("contactID", contactID);
$("#box").append(theLink);

答案 1 :(得分:0)

我发现的正确方法是(使用jQuery)$.each()函数:

  var theDIV = $('#1234DIV');
  $.each(theJSON.contacts, function (index, contact) {
    var theContact = theJSON.contacts[i];
    var contactID = theContact.contact_id;

    var theLink = $('<a>',{
      'id': 'Acontact_'+contactID,
      'href':'javascript:;',
    }).on('click', function(event) {
      console.log(event);
      console.log(contactID);
      alert(contactID);
    }).html(theContact.name_display);

    theDIV.append(theLink);
  }

它有效!!