gpt4 book ai didi

javascript - 替换以特定文本开头的元素的文本

转载 作者:行者123 更新时间:2023-11-27 22:53:22 26 4
gpt4 key购买 nike

我有类似 html 的底部代码

<table>
<tr>
<td>
{name length='100'}
</td>
<td>
{otherText length='100'}
</td>
<td>
{otherText2 length='100'}
</td>
</tr>
</table>

我想更改以 {name 开头的 td 文本。

我该怎么做?

最佳答案

如果您想替换以 {name 开头的整个内部文本,请尝试以下操作:

// added this condition to have the startsWith function in all browsers
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
}

function replace(newVal) {
var tds = document.getElementsByTagName("td");
for (var i = 0; i < tds.length; i++) {
var elem = tds[i];
if ( elem.innerText.startsWith("{name") ) {
elem.innerText = newVal;
}
}
}

replace("new-value");
<body>
<table>
<tr>
<td>
{name length='100'}
</td>
</tr>
</table>
</body>

编辑:

正如 Mohammad 提到的,并非所有浏览器都支持 startsWith 方法。见下表:

╔═══════════════╦════════╦═════════╦═══════╦═══════════════════╦═══════╦════════╗
║ Feature ║ Chrome ║ Firefox ║ Edge ║ Internet Explorer ║ Opera ║ Safari ║
╠═══════════════╬════════╬═════════╬═══════╬═══════════════════╬═══════╬════════╣
║ Basic Support ║ 41 ║ 17 ║ (Yes) ║ No Support ║ 28 ║ 9 ║
╚═══════════════╩════════╩═════════╩═══════╩═══════════════════╩═══════╩════════╝

这就是为什么我添加了上面的条件 - 在所有浏览器中都具有 startsWith 函数。

关于javascript - 替换以特定文本开头的元素的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37855267/

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