繁体   English   中英

在 div jQuery 中创建 H1 元素

[英]Create H1 element in div jQuery

我想在 HTML 的 div 元素中添加一个<h1></h1>元素和 jQuery。 我该怎么做呢?

 function show() { let text = "greetings" let divElem = document.getElementById("hello"); divElem.innerHTML = '<h1>${text}</h1>' }
 <div id="hello"></div> <button onclick="show()">show</button>

基本上,我想在 div 元素中创建一个 h1 元素,它显示文本变量中包含的字符串,“greetings”我该怎么做?

你需要'而不是'?!

也可以在这个链接中阅读它: 模板文字(模板字符串)

 function show() { let text = "greetings" let divElem = document.getElementById("hello"); divElem.innerHTML = `<h1>${text}</h1>` }
 <div id="hello"></div> <button onclick="show()">show</button>

您可以使用 Jquery .html()方法。

此外,您必须使用反引号而不是引号。 (`) 以便在“字符串”中使用模板。 这称为模板文字。 你可以在这里阅读更多关于它们的信息

 function show() { let text = "greetings" $( "#hello" ).html( `<h1>${text}</h1>` ); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="hello"></div> <button onclick="show()">show</button>

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM