javascript - 读取文本值并更改字符串值?

标签 javascript html css

我在下面有以下代码。我想更改 H2 消息 No results were found for this query: <em class="querytext">类似于 "No results were found by hello world!没有硬编码,因为我无法控制 HTML 文件中的一段文本,他们是否可以通过 if 条件 CSS 或 JS 读取字符串然后在页面加载时更改消息?类似 if text == No results were found for this query: 的东西展示"No results were found by hello world! .

<div class="search-results">
    <h2>No results were found for this query: <em class="querytext"></em></h2>
</div>

最佳答案

您可以尝试使用 JavaScript 操作 DOM:

<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
      <script type="text/javascript">
          function updateResultText(text) {
            var resultTextEl = document.querySelector('.search-results > h2');
            if(resultTextEl) {
              resultTextEl.innerText = "No results were found by " + text;
            }
          }
    </script>
    <button onclick="updateResultText('hello world!')">Update Text</button>
   <div class="search-results">
     
    <h2>No results were found for this query: <em class="querytext"></em>
    </h2>
  </div>
  </body>
</html>

你需要的JS如下:

function updateResultText(text) {
            var resultTextEl = document.querySelector('.search-results > h2');
            if(resultTextEl) {
              resultTextEl.innerText = "No results were found by " + text;
            }
          }

然后,您可以调用 updateResultText,并包含您希望“by”之后的文本包含的任何内容。

关于javascript - 读取文本值并更改字符串值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59143681/

相关文章:

javascript - Ext JS 中TreeStore 不能实现filterBy 方法吗?

javascript - 动态添加的输入字段未提交

javascript - Jquery 在多个图像上添加 mouseup 和 mousedown 事件

html - 导航栏端盖

html - 背景大小 polyfill 在 IE8 中不起作用?

jquery - Bootstrap : vertical align to bottom/same column height

javascript - 从 Angular 中的 api 导入样式

javascript - jQuery donut 插件 : Arrow doesn't show on print

css - 在 div 中安装 iframe

css - 表情符号在 IOS 7 上不会超过 16px 字体大小