gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 10:07:47 24 4
gpt4 key购买 nike

我在下面有以下代码。我想更改 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com