将对象从getJSON传递到外部函数?

时间:2018-11-16 21:47:23

标签: jquery

我试图将对象“值”传递给“ hello()”函数,但出现以下错误:

  

SyntaxError:缺少]元素列表注释后:[在第1行打开   第6栏

我的代码:

$(document).ready(function(){
    $.getJSON("http://localhost:8080/api/users/all", function(result){
        $.each(result, function(key,value) {
            $("#data").append(
              '<li class="list-group-item\">' + 
                value.name + 
                '<a class="btn btn-light float-right" onclick="hello(' + value + ')" role="button">View Euclidean</a>' + 
                '<a class="btn btn-dark float-right mr-1 text-light" role="button">View Recommendations</a>' + 
              '</li>');
        });
    });
});

function hello(value) {
    console.log("hello" + value.name);
}

我在这里做错什么了吗?

2 个答案:

答案 0 :(得分:0)

您正在尝试将对象附加到字符串:

'<a class="btn btn-light float-right" onclick="hello(' + value + ')" role="button">View Euclidean</a>'

...这将导致在对象上调用toString,该对象通常转换为:

[Object object]

...出现语法错误,因为您的onclick现在为:

hello([Object object])

...这是语法错误。

您可能打算做+ JSON.stringify(value) +

更好的方法是不通过字符串操作创建点击处理程序:

const euclideanLink = $('<a class="btn btn-light float-right" role="button">View Euclidean</a>');
euclideanLink.click(e => {
  e.preventDefault();
  hello(value.name);
  return false;
});
const recommendsLink = $('<a class="btn btn-dark float-right mr-1 text-light" role="button">View Recommendations</a>');

const listItem = $('<li class="list-group-item"/>');
listItem.append(value.name, euclideanLink, recommendsLink);

$("#data").append(listItem);

答案 1 :(得分:0)

我强烈建议您将标记与javascript分开,并将事件处理程序动态绑定到链接,因此您不必担心将其转换为字符串或其他任何东西。

//$(document).ready(function() {
//  $.getJSON("http://localhost:8080/api/users/all", function(result) {

    //fake out some results so we can see the logic in action
    var result = [
      { id: 1, name: 'Jane' },
      { id: 2, name: 'Jim' }
    ];
    
    //get the html from the template on the page so we don't have to put
    //it in the script
    var userTemplate = $('#userTemplate').html();
    
    $('#data').append(
      //create an array of all the elements to add to the data
      //doing this lets us append once, reducing the number of times we
      //touch the DOM
      $.map(result, function(value){
        //replace the {{name}} in the template with our real name
        var $newUser = $(userTemplate.replace(/\{\{name\}\}/, value.name));
        
        //find the first link and bind the click handler to it
        $newUser.find('.view-euclidean').on('click', function(){
          hello(value);
        });
        
        return $newUser;
      })
    );
//  });
//});

function hello(value) {
  console.log("hello" + value.name);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="data"></div>

<script type="text/html" id="userTemplate">
  <li class="list-group-item">
    {{name}}
    
    <a class="btn btn-light float-right view-euclidean" role="button">
      View Euclidean
    </a>
    
    <a class="btn btn-dark float-right mr-1 text-light" role="button">
      View Recommendations
    </a>
  </li>
</script>

相关问题