简体   繁体   English

JavaScript innerHTML 未设置元素样式

[英]JavaScript innerHTML not setting the element style

Ran into a problem in JavaScript writing HTML code into innerHTML.在 JavaScript 中将 HTML 代码写入 innerHTML 时遇到问题。 Here is a very simple case I recreated.这是我重新创建的一个非常简单的案例。 The problem is in the element style seems taking no effect, either using old font size or CSS style.问题在于元素样式似乎没有效果,无论是使用旧字体大小还是 CSS 样式。 The code has been tested on FireFox and Chrome in XAMPP localhost, and got same result.该代码已在 XAMPP localhost 中的 FireFox 和 Chrome 上进行了测试,并得到了相同的结果。 The text would be shown correctly but the style wouldn't.文本将正确显示,但样式不会。 Any suggestion?有什么建议吗?

 tDoc = document.getElementById('target'); tDoc.innerHTML = "<p><font size='+5'>"; tDoc.innerHTML += document.getElementById("srcBox").value; tDoc.innerHTML += "</font></p>"; tDoc.innerHTML += "<p style='font-size:20px;'>"; tDoc.innerHTML += document.getElementById("srcBox").value; tDoc.innerHTML += "</p>";
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>JavaScript innerHTML not setting the element style</title> </head> <body> <input type="text" name="ttBox" id="srcBox" value="My Title 2"> <div id="target">NA</div> </body> </html>

You can't add partial tags to the DOM like that.你不能像那样向 DOM 添加部分标签。 The browser will not see the tags as belonging to a single element and possibly attempt to construct closing tags for the partial tag you append.浏览器不会将标签视为属于单个元素,并且可能会尝试为您附加的部分标签构造结束标签。

The simplest change is to add all of your HTML at once:最简单的更改是一次添加所有 HTML:

tDoc = document.getElementById('target');
tDoc.innerHTML = "<p><font size='+5'>"
               + document.getElementById("srcBox").value
               + "</font></p>"
               + "<p style='font-size:20px;'>"
               + document.getElementById("srcBox").value
               + "</p>";

Additionally, you may want to escape the values obtained from the inputs.此外,您可能希望转义从输入中获得的值。 You can either manually escape them, or you can more effectively construct the individual DOM elements themselves rather than using a string.您可以手动对它们进行转义,也可以更有效地自己构造单个 DOM 元素,而不是使用字符串。

tDoc = document.getElementById('target');
const p = document.createElement('p');
const font = document.createElement('font');
font.setAttribute('size', '+5');
font.textContent = document.getElementById("srcBox").value;
p.appendChild(font);
const p2 = document.createElement('p');
p2.style.fontSize = '20px';
p2.textContent = document.getElementById("srcBox").value;
tDoc.innerHTML = '';
tDoc.appendChild(p);
tDoc.appendChild(p2);

The use of textContent to insert the text will prevent the injection of text as HTML code that could manipulate the DOM and cause unexpected behavior.使用textContent插入文本将防止将文本作为 HTML 代码注入,该代码可能会操纵 DOM 并导致意外行为。

Don't append to innerHTML in multiple steps like that.不要像这样在多个步骤中附加到innerHTML Each time you assign to innerHTML it parses the element completely to create the new DOM.每次分配给innerHTML时,它都会完全解析元素以创建新的 DOM。 If there are missing closing tags, it adds them.如果缺少结束标签,它会添加它们。 So when you do所以当你这样做时

tDoc.innerHTML = "<p><font size='+5'>";

it's actually as if you did实际上就像你做了

tDoc.innerHTML = "<p><font size='+5'></font></p>";

Then your next addition is outside the <font> tag, so it doesn't get the style.然后你的下一个添加在<font>标记之外,所以它没有得到样式。

Put everything into a single string and assign it to innerHTML all at once.将所有内容放入一个字符串中,并一次性将其分配给innerHTML

 tDoc = document.getElementById('target'); let html = "<p><font size='+5'>"; html += document.getElementById("srcBox").value; html += "</font></p>"; html += "<p style='font-size:20px;'>"; html += document.getElementById("srcBox").value; html += "</p>"; tDoc.innerHTML = html;
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>JavaScript innerHTML not setting the element style</title> </head> <body> <input type="text" name="ttBox" id="srcBox" value="My Title 2"> <div id="target">NA</div> </body> </html>

Every time assign to the .innerHTML of an element, the browser will do its best to make sense of the input and will produce markup as a result.每次分配给元素的.innerHTML时,浏览器都会尽最大努力理解输入并生成标记作为结果。 If the input is malformed and not valid syntax, the browser will make what it can from it and do its best to produce valid elements and markup as a result.如果输入格式错误且语法无效,浏览器将尽其所能,并尽其所能生成有效的元素和标记作为结果。

The generated markup/elements will always be well-formed;生成的标记/元素总是格式正确的; at no point in the JavaScript is the structure in the DOM invalid. JavaScript 中的任何时候 DOM 中的结构都无效。

When this line is run:运行此行时:

tDoc.innerHTML = "<p><font size='+5'>";

The browser will see that there's no trailing <font> or <p> - but the resulting structure must be valid, so it ends those tags for you.浏览器将看到没有尾随的<font><p> - 但生成的结构必须是有效的,因此它会为您结束这些标签。 After that line runs, the #target element contains:该行运行后, #target元素包含:

<p><font size="+5"></font></p>

Then the next line runs:然后下一行运行:

tDoc.innerHTML += document.getElementById("srcBox").value;

But the browser has already ended the <p> and <font> tags - so that value doesn't get inserted inside those, but as a plain text node as a direct child of the #target .但是浏览器已经结束了<p><font>标记 - 因此该值不会插入其中,而是作为纯文本节点作为#target的直接子节点。

The pattern continues for the rest of your code.该模式在您的其余代码中继续存在。

Assign the HTML string all at once, so that the DOM structure isn't created piecemeal.一次性分配所有的 HTML 字符串,这样 DOM 结构就不会被零碎地创建。

 tDoc = document.getElementById('target'); tDoc.innerHTML = ` <p><font size='+5'> ${document.getElementById("srcBox").value} </font></p> <p style='font-size:20px;'> ${document.getElementById("srcBox").value} </p> `;
 <input type="text" name="ttBox" id="srcBox" value="My Title 2"> <div id="target">NA</div>

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

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