JavaScript - 为什么 innerHTML 属性 在包含 HTML 时显示为文本?
JavaScript - Why is innerHTML property displaying as text when it contains HTML?
我在 ASP.CORE 视图中执行了以下 JS 代码,主要用于设置页面上元素的内容。
if (notificationBanner) {
var bannerText = unescape("@ViewData.GetClient().GetText("$.resetCredentials.step2.otpSendBanner")");
console.log(bannerText);
notificationBanner.innerHTML = bannerText;
}
正在浏览器控制台中记录以下内容:
<p>A One Time Password (OTP) has been sent to your mobile number below. Enter the OTP in the field below. <strong>The OTP is valid for 10 minutes</strong>.</p>

元素最终是这样的:
然而这是不正确的,我希望 <strong></strong>
中的部分是粗体。为什么将其添加为文本?
我一直在寻找普通的 JS 解决方案,所以查看了提供的 post 蜡笔。找到了一个很好的解决方案。感谢您的帮助。
function decodeHtml(html) {
var txt = document.createElement("textarea");
txt.innerHTML = html;
return txt.value;
}
if (notificationBanner) {
var bannerText = unescape("@ViewData.GetClient().GetText("$.resetCredentials.step2.otpSendBanner")");
console.log(bannerText);
notificationBanner.innerHTML = decodeHtml(bannerText);
}
我在 ASP.CORE 视图中执行了以下 JS 代码,主要用于设置页面上元素的内容。
if (notificationBanner) {
var bannerText = unescape("@ViewData.GetClient().GetText("$.resetCredentials.step2.otpSendBanner")");
console.log(bannerText);
notificationBanner.innerHTML = bannerText;
}
正在浏览器控制台中记录以下内容:
<p>A One Time Password (OTP) has been sent to your mobile number below. Enter the OTP in the field below. <strong>The OTP is valid for 10 minutes</strong>.</p>

元素最终是这样的:
然而这是不正确的,我希望 <strong></strong>
中的部分是粗体。为什么将其添加为文本?
我一直在寻找普通的 JS 解决方案,所以查看了提供的 post 蜡笔。找到了一个很好的解决方案。感谢您的帮助。
function decodeHtml(html) {
var txt = document.createElement("textarea");
txt.innerHTML = html;
return txt.value;
}
if (notificationBanner) {
var bannerText = unescape("@ViewData.GetClient().GetText("$.resetCredentials.step2.otpSendBanner")");
console.log(bannerText);
notificationBanner.innerHTML = decodeHtml(bannerText);
}