$.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);
}
如何在此处正确插入e._id
,以便将文章ID设为?
当我点击此按钮时,它会显示:
(index):1 Uncaught SyntaxError:无效或意外的令牌
答案 0 :(得分:0)
使用jQuery创建按钮时出现语法错误。你错过了id的单引号。你也错过了一些牙箍。
<button onclick=crud.remove(" + e._id + ")>Remove</button><br>
将此行替换为
<button onclick=crud.remove('" + e._id + "')>Remove</button><br>
我已更正您的代码:
$.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>