javascript
  • jquery
  • 2016-09-22 67 views 0 likes 
    0

    如何添加单击事件TOT按钮串

    $.ajax({ 
     
    \t \t url:'/getArticles', 
     
    \t \t method:'GET', 
     
    \t }).done(function(articles){ 
     
    \t \t var content = ''; 
     
    \t \t articles.forEach(function(e){ 
     
    \t \t \t var res = "<div class='article'>" + 
     
    \t \t \t \t \t \t "<h3>" + e.title + "</h3>" + 
     
    \t \t \t \t \t \t "<p>" + e.content + "</p><br>" + 
     
    \t \t \t \t \t \t "<button onclick=crud.remove(" + e._id + ")>Remove</button><br>" + 
     
    \t \t \t \t \t "</div>"; 
     
    \t \t \t content += res; 
     
    \t \t }); 
     
    \t \t $('#allarticles').append(content); 
     
    \t }); 
     
    \t window.crud = (function(){ 
     
    \t \t // Remove an article 
     
    \t \t function remove(id){ 
     
    \t \t \t console.log(id); 
     
    \t \t }

    如何插入e._id正确这里,所以它会把项目的ID?

    当我点击这个按钮,它说:

    (index):1 Uncaught SyntaxError: Invalid or unexpected token

    +0

    把参数报价:'“<按钮的onclick = \“crud.remove('”+ e._id +'“)\”>删除“” –

    回答

    0

    有使用jQuery在您的按钮创建语法错误。你遗漏了id的单引号。你也错过了一些大括号。

    <button onclick=crud.remove(" + e._id + ")>Remove</button><br> 
    

    与此

    <button onclick=crud.remove('" + e._id + "')>Remove</button><br> 
    

    更换你上面的行我已经纠正代码:

    $.ajax({ 
     
    \t \t url : '/getArticles', 
     
    \t \t method : 'GET', 
     
    \t }).done(
     
    \t \t \t function(articles) { 
     
    \t \t \t \t var content = ''; 
     
    \t \t \t \t articles.forEach(function(e) { 
     
    \t \t \t \t \t var res = "<div class='article'>" + "<h3>" + e.title 
     
    \t \t \t \t \t \t \t + "</h3>" + "<p>" + e.content + "</p><br>" 
     
    \t \t \t \t \t \t \t + "<button onclick=crud.remove('" + e._id 
     
    \t \t \t \t \t \t \t + "')>Remove</button><br>" + "</div>"; 
     
    \t \t \t \t \t content += res; 
     
    \t \t \t \t }); 
     
    \t \t \t \t $('#allarticles').append(content); 
     
    \t \t \t }); 
     
    \t window.crud = (function() { 
     
    \t \t // Remove an article 
     
    \t \t function remove(id) { 
     
    \t \t \t console.log(id); 
     
    \t \t } 
     
    \t });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    相关问题