将js对象值作为字符串复制到html中

Copying the js objects value into the html as string

本文关键字:复制 html 字符串 js 对象      更新时间:2023-09-26

我想使用非全局的javascript对象的值来创建html元素。

如果我运行以下代码,我会收到错误:"params未定义"。我想做的只是将值作为参数复制到html代码中。

if (params.data.allowedOperations.indexOf('Put') != -1) {
   return "<a onclick='"ahey('PUT',params.data.allowedOperations)'" href='"#'"> PUT </a>";
}

您可以使用:

if (params.data.allowedOperations.indexOf('Put') != -1) {
    return "<a onclick='"ahey('PUT','"+params.data.allowedOperations+"')'" href='"#'"> PUT </a>";
}

或者,您可以创建一个锚节点,然后向其添加一个事件侦听器,或者将操作存储在不同的属性中,例如:

if (params.data.allowedOperations.indexOf('Put') != -1) {
    return "<a onclick='"ahey('PUT', this.dataset.allowedOperations)'" data-allowed-operations='""+params.data.allowedOperations+"'" href='"#'"> PUT </a>";
}

尝试

return "<a onclick='"ahey('PUT','" + params.data.allowedOperations + "')'" href='"#'"> PUT </a>";

由于params.data.allowedOperations是一个字符串,您需要在引号周围添加单引号。如果是数字,则不需要这些。

相关文章: