【问题标题】:How to add click event tot button in string如何将点击事件添加到字符串中的按钮
【发布时间】:2016-09-22 12:56:49
【问题描述】:

$.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: Invalid or unexpected token

【问题讨论】:

  • 将参数放在引号中:"&lt;button onclick=\"crud.remove('" + e._id + '")\"&gt;Remove&lt;/button&gt;&lt;br&gt;"

标签: javascript jquery


【解决方案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);
		}
	});
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    相关资源
    最近更新 更多