jQuery,将对象从数组传递到另一个函数

时间:2018-06-08 16:32:43

标签: javascript jquery

我有一个对象列表进入我的网页。该对象的一个​​属性是firstName。我显示了一些属性,并有一个可点击的属性调用另一个功能。我想将对象从数组传递给第二个函数

jQuery.each(x, function () {
            $('#results').append("<a href='javascript:void(0)' onClick='workSup(" + '"' + $(this) + '"' + ")' >" + decodeURI(this.firstName) + ' ' + decodeURI(this.lastName) + " - " + decodeURI(this.preApprovalSupervisorName) + " <a/><br/> ");
        });

 function workSup(x) {

        alert(x.firstName);
    }

我试过传递这个以及$(这个)。警报显示为“未定义”

我做错了什么?谢谢!

4 个答案:

答案 0 :(得分:0)

jQuery.each(x, function() {
  //create the a element
  var $a = $("<a href='javascript:void(0)'>"+
                 decodeURI(this.firstName) +' '+ decodeURI(this.lastName) +
                 " - "+ decodeURI(this.preApprovalSupervisorName) +
             "</a><br/>");

  //bind the event handler to it
  $a.on('click', function(){
      workSup(x);
  });
});

答案 1 :(得分:0)

jQuery有一个很棒的函数,.data(),我建议你研究一下:

$('#selector').data("key", "value (string, number, object, etc.)")
$('#selector').data("key");  //Returns the data, or null if not yet set

此外,我强烈建议远离onclick

$('.myClassName').on("eventName (such as click, change or keyup)", "jqSelector", handlerFunction);

var x = [{firstName:"John", lastName:"Lennon"}, {firstName:"Phil", lastName:"Ochs"}]

$(document).ready(function() {
  jQuery.each(x, function () {
      var linkEl = $('<a class="myLink" href="javascript:void(0)">' + this.firstName + " " + this.lastName + '</a>');
      linkEl.data("myObjData", this);
      $('#results').append(linkEl);
  });
  $(document).on("click", ".myLink", function() {
       var myObjData = $(this).data("myObjData");
       //myObjData.firstName can be accessed here
       alert(JSON.stringify(myObjData));
  });
});
<html>
  <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  </head>
  <body>
    <div id="results"></div>
  </body>
</html>

$('。myClass')。on()甚至比$('。myClass')更好。单击()因为它甚至会监听稍后动态添加的元素

答案 2 :(得分:0)

如@taplar所述,您正在创建内联绑定。基本上会发生的事情是你的$(this)被解析为字符串,然后你的workSup()方法中你试图访问字符串的firstName属性,这显然是未定义的。

您需要做的是动态创建链接并将事件监听器附加到它(在其中调用workSup()方法),如下所示:

// Your data
const x = [
  { firstName: 'First', lastName: 'Last', preApprovalSupervisorName: 'Super' },
  { firstName: 'Another', lastName: 'One', preApprovalSupervisorName: 'His super' },
];

// Your workSup method
const workSup = x => alert(x.firstName);

// Loop though each item
$.each(x, function() {
  // Create new <a> element
  const $element = $('<a></a>')
    // Add href attribute
    .attr('href', 'javascript:void(0)')
    // Set its text
    .text(`${decodeURI(this.firstName)} ${decodeURI(this.lastName)} ${decodeURI(this.preApprovalSupervisorName)}`)
    // Attach onClick listener
    .on('click', () => workSup(this));
  
  // Append the element to the results and add line break
  $('#results')
    .append($element)
    .append('<br />');
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="results"></div>

答案 3 :(得分:0)

&#13;
&#13;
var x =[{firstName: "John", lastName:"DG", preApprovalSupervisorName: "sup"}];

jQuery.each(x, function (index, value) {
            $('#results').append(
            $("<a>")
            	.attr("href","#")
            	.html( decodeURI(value.firstName) + ' ' + decodeURI(value.lastName) + " - " + decodeURI(value.preApprovalSupervisorName))
              .click(function(){
              workSup(value);
              
              })
            );
        });

 function workSup(x) {

        alert(x.firstName);
    }
&#13;
&#13;
&#13;