【问题标题】:Is it possible to replace text with another just with JS?是否可以仅使用 JS 将文本替换为另一个文本?
【发布时间】:2018-09-21 06:34:38
【问题描述】:

我在标题中有这段代码:

<h1 class="header-title">
  <span>Title</span>
</h1>

然后在页面内容上我有:

<div id="content">
  <h1 class="category-title">Nike</h1>
</div>

我无法在后端编辑标题,我只能在标签前添加 JS 代码。所以我的问题是,可以使用 JS 并从内容中获取标题并将其替换为标题中的 h1 标题吗?标题中的标题在所有页面上都相同,我希望有“类别标题”。

【问题讨论】:

  • 发布的问题似乎根本没有包含any attempt 来解决问题。 StackOverflow 期待您 try to solve your own problem first,因为您的尝试有助于我们更好地了解您想要什么。请编辑问题以显示您尝试过的内容,以说明您在minimal reproducible example 中遇到的特定问题。欲了解更多信息,请参阅How to Ask 并拨打tour
  • This 是您的起点。 :-)
  • 回答您的问题,“是的,有可能”。
  • 您能告诉我们到目前为止您对这个问题的看法吗?
  • 好吧,我只是 Javascript 的新手,我的日常工作是 HTML 和 CSS。我知道如何在 JS 中用另一个文本替换文本。但不知道如何查找和替换另一个文本。我不需要整个代码,只是不想帮助从哪里开始:-)

标签: javascript html


【解决方案1】:

您需要为DOMContentLoaded-event 添加一个事件监听器(这确保Javascript 可以访问页面上的元素)。在这个监听器中,从一个元素中读取文本并将另一个元素的文本设置为它:

document.addEventListener('DOMContentLoaded', function() {
  let headline = document.querySelector('#content h1.category-title').textContent;
  document.querySelector('h1.header-title span').textContent = headline;
})
<h1 class="header-title">
  <span>Title</span>
</h1>

<div id="content">
  <h1 class="category-title">Nike</h1>
</div>

【讨论】:

  • @JaniceZhong 无需编辑,该帖子提到了一种特殊情况,即 OP 将部分脚本声明为 type="text/babel",因此客户端 Babel 进程将对其进行转换。
【解决方案2】:

document.getElementById("title").innerText = document.getElementById("content").innerText;
<h1 class="header-title">
  <span id="title">Title</span>
</h1>

<div id="content">
  <h1 id="content" class="category-title">Nike</h1>
</div>

【讨论】:

    【解决方案3】:

    但这是可能的。

    <h1 class="header-title">
        <span id="title">Title</span> <!-- add some title !--> 
     </h1>
    
    <div id="content">
      <h1 id="category_title" class="category-title">Nike</h1> <!-- add some title !-->
    

    在你的 js 上

    <script>
       var title = document.getElementById('title'); //get the element of the header
       var category_title = document.getElementById('category_title'); //get the element of the category
       title.innerHTML = category_title.innerHTML;  //the content of category will now be the content of you title
    </script>
    

    希望对你有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-16
      • 1970-01-01
      • 2012-12-21
      • 2023-03-10
      • 1970-01-01
      相关资源
      最近更新 更多