首页 > 解决方案 > 将 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 按钮时可以移动该值。

我怎样才能做到这一点?

标签: javascripthtml

解决方案


问题是 HTML 解析器为onEventName属性生成的函数不是在函数范围内创建的。因此,

 onclick='commentMod(result[i].content)

将尝试在全局范围内而不是在处理程序的函数范围内查找result和。可以设计一种涉及使用调用生成表格元素并在 JavaScript 中添加事件侦听器的解决方案,但缺乏 HTML 生成的简单性。isuccessdocument.createElement

在 HTML 中生成处理程序的一种方法是在转义后将 的值插入result[i].contentonclick属性值中,以免干扰 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)}"))'/>`;

推荐阅读