“ .innerhtml”未正确显示在Safari上(JavaScript)

发布于 2025-02-03 20:50:41 字数 1362 浏览 3 评论 0原文

我的问题:

嘿,大家,

我目前正在尝试编写一些简单的代码,以使用特定的字符串,并仅使用JavaScript使它们大胆。该代码正常运行,但是在移动设备上测试它时,我注意到它不能正确显示新的粗体字符串。

相反,它没有显示任何内容。

有人可以帮我吗?

我尝试的是:

我认为也许自从我使用“ .innerhtml”而不是“ .innertext”替换文本以来,它引起了某种问题,但是,我需要使用。正在返回的是HTML格式化(例如< b> {insert String esl eker on此处}</b>)。

我尝试设置元素的内部文本等于它们的内部HTML,但这导致每个字符串显示为“ < b> {insert string}</b>“而不是仅仅是”仅大胆的文字。

我的代码:

var text = document.getElementsByClassName('text-bold')
var boldText = []

for (i = 0; i < text.length; i++) { // For all of the elements with the class "text":
  var str = text[i].innerText // Get the inner text
  var bold = str.bold() // Make the inner text bold
  boldText.push(bold) // Return the string to an array
}

for (i = 0; i < text.length; i++) { // For all of the elements with the class "text":
  text[i].innerHTML = boldText[i] // Replace the inner HTML with the corresponding bold text from the array
}
<div>
  <p class="text-bold">Hello!</p>
  <p class="text">Hi!</p>
  <p class="text-bold">Hey!</p>
</div>

更新:

我最初认为这是移动设备的问题,但这似乎只是Safari的问题。

My Problem:

Hey Everyone,

I'm currently trying to write some simple code that takes specific strings and makes them bold using only JavaScript. The code works fine, but when testing it on mobile I noticed that it doesn't display the newly boldened string correctly.

Instead, it doesn't display anything.

Can anyone help me out with this?

What I've Tried:

I thought that maybe since I was replacing the text using ".innerHTML" rather than ".innerText" it was causing some sort of issue, however, I need to use ".innerHTML" since the string that JavaScript is returning is in HTML formatting (ex. <b>{Insert string here}</b>).

I tried setting the inner text of the elements equal to their inner HTML, but that resulted in each string being displayed as "<b>{Insert string here}</b>" rather than just the bold text alone.

My Code:

var text = document.getElementsByClassName('text-bold')
var boldText = []

for (i = 0; i < text.length; i++) { // For all of the elements with the class "text":
  var str = text[i].innerText // Get the inner text
  var bold = str.bold() // Make the inner text bold
  boldText.push(bold) // Return the string to an array
}

for (i = 0; i < text.length; i++) { // For all of the elements with the class "text":
  text[i].innerHTML = boldText[i] // Replace the inner HTML with the corresponding bold text from the array
}
<div>
  <p class="text-bold">Hello!</p>
  <p class="text">Hi!</p>
  <p class="text-bold">Hey!</p>
</div>

UPDATE:

I initially thought this was an issue with mobile, but it seems as if it's only an issue with Safari.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文