我有html像底码
<table>
<tr>
<td>
{name length='100'}
</td>
<td>
{otherText length='100'}
</td>
<td>
{otherText2 length='100'}
</td>
</tr>
</table>
我想更改以td
开头的{name
文字。
我该怎么做?
答案 0 :(得分:1)
如果要替换以{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
功能。
答案 1 :(得分:1)
您可以使用jquery text(function)
来迭代所有td
文本,并使用match()
按正则表达式检查文本内容。
$("td").text(function(index, text){
if (text.trim().match(/^{name/))
return "Changed text";
});
&#13;
table, tr, td {
border: 1px solid black;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
{name length='100'}
</td>
<td>
{type length='100'}
</td>
<td>
{other length='100'}
</td>
</tr>
</table>
&#13;
答案 2 :(得分:-1)
$('td').html('{name '+new_text);