javascript - 将 html 值放入 onClick()
问题描述
var content;
function listReply2() {
$.ajax({
type: "get",
contentType: "application/json",
url: "${contextPath}/comment/listJson.do?bno=${article.articleNO}",
success: function(result) {
var output = "<table>";
for (let i in result) {
output += "<tr>";
output += "<td>" + result[i].writer;
output += "(" + changeDate(result[i].regdate) + ")</td>";
output += "<td >" + result[i].content + "</td>";
if (member_id != null) {
output += "<td><input type='button' id ='rno' value='mod' onclick='commentMod(result[i].content)'/>";
output += "<input type='button' value='delete' onclick=''/></td>";
}
output += "</tr>";
}
output += "</table>";
$("#comment").html(output);
}
});
我想将 HTML 值result[i].content
放入 onClick 函数中,以便在按下 mod 按钮时可以移动该值。
我怎样才能做到这一点?
解决方案
问题是 HTML 解析器为onEventName
属性生成的函数不是在函数范围内创建的。因此,
onclick='commentMod(result[i].content)
将尝试在全局范围内而不是在处理程序的函数范围内查找result
和。可以设计一种涉及使用调用生成表格元素并在 JavaScript 中添加事件侦听器的解决方案,但缺乏 HTML 生成的简单性。i
success
document.createElement
在 HTML 中生成处理程序的一种方法是在转义后将 的值插入result[i].content
到onclick
属性值中,以免干扰 HTML 解析,然后在调用commentMod
.
请注意,代码片段示例仅使用escape
并且unescape
因为被编码的字符串不是URL 的一部分。
"use strict";
let result = [{content: "I'm < than a teapot & > than a coffee \"jar\""}];
let i = 0;
let html = `<span onclick='alert(unescape("${escape(result[i].content)}"))'>Click Me</span>`;
document.body.innerHTML = html;
console.log( html);
因此尝试更换
output += "<td><input type='button' id ='rno' value='mod' onclick='commentMod(result[i].content)'/>";
和
output += `<td><input type='button' id ='rno' value='mod'
onclick='commentMod(unescape("${escape(result[i].content)}"))'/>`;
推荐阅读
- sql - 使用 SQL 2008 的不同记录之间的部分总和
- r - 在R中查找多边形的最近邻
- python - 有没有办法从 return 语句中分离两个值?
- ios - 在嵌入式 SFSafariViewController 中打开通用链接
- python - 在python中选择排序算法
- javascript - 条形图 d3 条形下方的圆圈
- c# - 具有动态属性的 EF 查询
- python - 编写机器学习分类器算法
- javascript - jQuery .on("click", ".dropdown-menu li a", function () not working
- python - (Discord.py)我如何创建一个命令来给你一个指定的角色?