简体   繁体   English

我应该如何使用javascript更改带有变量的注入HTML元素?

[英]How should I change an injected HTML element with variable using javascript?

Question: What is the best practice to inject HTML, that contains javascript? 问题:注入HTML的最佳实践是什么,包含javascript?

Script to load content in page: 在页面中加载内容的脚本:

elmnt = document.getElementById("contentcontainer");
elmnt.innerHTML = this.responseText;

Page: 页:

Welcome to our restaurant!
<div id="contentcontainer"></div>

Responsetext: responseText的:

<div>
The menu for today:
<script> Script to get API resonse menu(today); <script>
</div>

So I'm injecting HTML that contains a script. 所以我正在注入包含脚本的HTML。 But the script is not executed. 但是脚本没有被执行。 How should I change variable HTML inside an injection? 我应该如何在注入中更改变量HTML?

您可以使用“ 模板字符串 ”并注入已处理的HTML。

I dont understand what the problem is. 我不明白问题是什么。 InnerHtml should work perfectly, as long as the variable is global and also you get the desire content. InnerHtml应该可以完美地工作,只要变量是全局的,你也可以获得所需的内容。

Here is an example of what i understod off what you want. 这是我想要了解你想要的东西的一个例子。

let str = '<p><script>var test="this is a test"</script></p>'

document.getElementsByTagName("BODY")[0].innerHTML  =str;

console.log(test) // and here is the injected script variable result

To get the content of the site from the url you will have to use a library like jq getscript Did i understand you correctly? 要从网址获取网站的内容,您将不得不使用像jq getscript这样的库我是否理解正确?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在元素中使用Javascript,并在jQuery中注入HTML - Using Javascript in an element with injected HTML in jQuery 如何使用 javascript 变量更改 html 文件中的文本? - How can I change text in an html file using a javascript variable? 如何使用JavaScript更改HTML元素值? - How to change HTML element value using javascript? 我可以使用Javascript更改HTML元素的ID吗? - Can I change the ID of an HTML element using Javascript? 您如何使用JavaScript访问注入HTML模板的值? - How do you access values injected into HTML templates using JavaScript? 使用 jQuery 或 javascript,我想知道 html 表的每列(1-4)中有多少个元素 500? 我该怎么做? - Using jQuery or javascript, I'd like to get that how many element 500 in each column (1-4) of an html table is ? How should I do it? 如何使用 Javascript 随机更改计时器上的 HTML 元素 - 跨越 web,而不仅仅是在浏览器中? - How do I randomly change an HTML element on a timer using Javascript - across the web, not just within the browser? 如何用 HTML 更改 javascript 变量? - How to change a javascript variable with HTML? 如何使用 JavaScript 中的变量更改元素的边距? - How can I change the margin of the element with a variable in JavaScript? 如何使用jQuery更改插入HTML文档中的JavaScript变量值 - How do I change a JavaScript variable value, inserted in a HTML document, using jQuery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM