js如何把html当字符串渲染到页面上

JavaScript07

js如何把html当字符串渲染到页面上,第1张

需要准备的材料分别有:电脑、html编辑器、浏览器。

1、首先,打开html编辑器,新建html文件,例如:index.html。

2、在index.html中的<script>标签,输入js代码:var a = '<input type="text" value="test" />'document.body.innerText = a。

3、浏览器运行index.html页面,此时html代码被当成字符串渲染到了页面上。

是你的写法有问题,在 HTML 中写事件函数是:

<div class="info"><img src="imageUri" alt="" onclick="showimg(imageUri)" /></div>

但是在 JS 中构建 HTML 的时候,方法名不能放在字符串外面作为 JS 代码执行,正确的应该是:

str += `<div class="info"><img src="${data.content.imageUri}" alt="" onclick="showimg(${data.content.imageUri})" /></div>`

我这里用的是模板字符串,用字符串拼接也是一样的,showimg 不能作一个方法在 JS 中调用,按你的写法,onclick 绑定的是 showimg(data.content.imageUri) 执行完成后的返回值。