[英]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); }
如何在此處正確插入e._id
,以便將其放置在文章ID中?
當我單擊此按鈕時,它說:
(索引):1未捕獲的語法錯誤:無效或意外的令牌
使用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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.