简体   繁体   中英

How to add click event tot button in string

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

How do I insert e._id correctly here so it will put id of article?

When I click this button it says:

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

There is syntax error in your button creation using jQuery. You missed single quotes for id. Also you were missing some braces.

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

Replace your above line with this

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

I have corrected your code :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM