如何使用 jquery 为所有 ID 添加标题
How to add title to all id's with jquery
如何为 table 中的所有 id 添加标题。
代码:
<table>
<tr>
<td id="A">TextA</td>
<td id="A">TextB</td>
<td id="A">TextC</td>
</tr>
</table>
$('#A')[0].title = "new title value";
这是 jsfiddle:http://jsfiddle.net/3hocugmj/
我试过这样的 for 循环:
for (b = 0; b < 3; b++) {
$('#A')[b].title = "new title value";
}
但这行不通...有什么解决办法吗?
非常感谢。
您的 HTML 无效 - 同一页面中不能有具有相同 id
的元素。使用 class 代替
<table>
<tr>
<td class="A">TextA</td>
<td class="A">TextB</td>
<td class="A">TextC</td>
</tr>
</table>
那么你的JS就变成了one-liner(假设你想让所有的元素都拥有相同的title
属性):
$('.A').prop('title', 'new title value');
如果他们需要不同的值,您可以给prop()
一个包含设置标题逻辑的函数:
$('.A').prop('title', function() {
return 'new title value: ' + $(this).text();
});
以上将产生以下值:
new title value: TextA
new title value: TextB
new title value: TextC
如何为 table 中的所有 id 添加标题。
代码:
<table>
<tr>
<td id="A">TextA</td>
<td id="A">TextB</td>
<td id="A">TextC</td>
</tr>
</table>
$('#A')[0].title = "new title value";
这是 jsfiddle:http://jsfiddle.net/3hocugmj/
我试过这样的 for 循环:
for (b = 0; b < 3; b++) {
$('#A')[b].title = "new title value";
}
但这行不通...有什么解决办法吗?
非常感谢。
您的 HTML 无效 - 同一页面中不能有具有相同 id
的元素。使用 class 代替
<table>
<tr>
<td class="A">TextA</td>
<td class="A">TextB</td>
<td class="A">TextC</td>
</tr>
</table>
那么你的JS就变成了one-liner(假设你想让所有的元素都拥有相同的title
属性):
$('.A').prop('title', 'new title value');
如果他们需要不同的值,您可以给prop()
一个包含设置标题逻辑的函数:
$('.A').prop('title', function() {
return 'new title value: ' + $(this).text();
});
以上将产生以下值:
new title value: TextA
new title value: TextB
new title value: TextC