我可以使用Element.insertAdjacentHTML()插入标签脚本 [英] Can I use Element.insertAdjacentHTML() to insert tag script

查看:38
本文介绍了我可以使用Element.insertAdjacentHTML()插入标签脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有来自客户端的对node.js的请求.Node.js响应字符串

i have request to node.js from client. Node.js response string

app.post('/verify',cors(issue2options), async (req, res) => {
let auth = await mongo({
    input:'express app',
    data:req.body['auth']['address'],
    type:'verify'
},'get', 'type')

if(empty(auth)){
    res.send(JSON.stringify(`

                                <div id="registration" slot="varan-about"> 
                                Войдите под аккаунтом администратора
                                <script type="module">

                                 console.log('sssss') 

                                <\/script>
                                </div>`))
}else{
    res.send(true)
}

})在客户端上,我将字符串插入document ['body']

}) On client I insert string to document['body']

 document['body'].insertAdjacentHTML('afterbegin', `${json}`);

但是随后我插入字符串脚本无效.

But then i insert string script no work.

是否可以使用此方法插入脚本?

Is it possible to insert a script using this method ?

推荐答案

来自官方HTML5规范:

使用innerHTML插入的

script元素在执行时不执行插入.

script elements inserted using innerHTML do not execute when they are inserted.

插入相邻的HTML与修改特定DOM元素的 innerHTML 相同.

Inserting the adjacent HTML is the same as modifying innerHTML of a specific DOM element.

如果您真的想从服务器中提供html,css和javascript的混合体,则可能需要将每个部分放到各自的属性中.例如: {"js":< Some js">," html:"< Some标记>," css:"< Some样式>}} 然后,在客户端,您可以创建一个脚本标记并将其内联到其中:

If you really want to provide a mixture of html, css and javascript back from your server, you might want to put each part into a respective property. For example: {"js": "<Some js here">, "html": "<Some markup here>", "css": "<Some styles here>"} Then, on the client side, you can create a script tag and inline your logic to it:

var script = document.createElement('script');
script.textContent = data.js;
document.body.appendChild(script);

可以用类似的方式处理样式:

The style could be handled in the similar fashion:

var style = document.createElement('style');
style.textContent = data.css;
document.head.appendChild(style);

最后,可以通过 innerHTML 更改标记,但是请记住,这不会删除附加到DOM元素的任何事件处理程序,这些事件处理程序在解析新HTML之后将被新元素替换:

Finally, the markup could be changed via innerHTML but keep in mind that this will not remove any event handlers attached to the DOM elements that will have been replaced by new elements after parsing new HTML:

var someNode = document.querySelector('<some selector>');
someNode.innerHTML = data.html;

这篇关于我可以使用Element.insertAdjacentHTML()插入标签脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆