javascript - 添加 REL 属性和附加 CLASS 属性的 Javascript 代码
问题描述
我正在寻找一些 Javascript 代码,它们会将 REL 属性添加到 A 链接元素中,然后将 CLASS 属性附加到其中的 Button 元素中。
<table>
<tbody>
<tr>
<td class="column-main">
Sample Text Here
</td>
<td class="column-url">
<a href="website.com"><button class="classNamehere">View</button></a>
</td>
</tr>
</tbody>
</table>
我想要目标 A 链接和其中的 Button 元素,以便将其更改为:
<a href="website.com" rel="iLightbox" ><button class="classNamehere fusion-lightbox-link">View</button></a>
这是我尝试过的...
$('.column-url a').attr( 'rel', 'iLightbox' );
$('.column-url button').attr( 'class', 'fusion-lightbox-link' );
解决方案
以下是三个示例,它们以不同的方式实现您想要的效果:
// This code would be the code working for your example, only get one element and apply the new attribute and class to id
var tableTd = window.getElementsByClassName('column-url')[0],
aLink = tableTd.getElementsbyTagName('a')[0],
aButton = aLink.getElementsbyTagName('button')[0];
aLink.setAttribute('rel', 'iLightbox');
aButton.classList.add('fusion-lightbox-link');
// This would work if you have the link and button inside a specific container (td for example)
var container = window.getElementsByClassName('column-url');
for( var i = 0; i < tableTd.length, i++)[
container[i].getElementsbyTagName('a')[0].setAttribute('rel', 'iLightbox');
container[i].getElementsbyTagName('a')[0].getElementsbyTagName('button')[0].classList.add('fusion-lightbox-link');
}
// This would look for all A tags with specific class name and set rel attribute to id, then find the button and add a class to it
var aLinks = window.getElementsByClassName('aClassName');
for( var i = 0; i < aLinks.length, i++)[
aLinks[i].setAttribute('rel', 'iLightbox');
aLinks[i].getElementsbyTagName('button')[0].classList.add('fusion-lightbox-link');
}
推荐阅读
- java - 如果在Java中提供偶数,为什么应该无限的while循环终止
- javascript - 我用于解析食品订单的简单 Javascript RegExp 正在嘲笑我
- amazon-web-services - Auto Scaling 组生命周期挂钩定期通知
- php - get_posts 的包含选项有效,但不限制帖子数量
- ios - 如何从集合视图单元格中调用 CollectionViewController
- java - Jline 终端编写器输出格式错误的输出
- r - 在R中自动设置变量的类?
- java - Java - 存储在文件中的盐值与从文件中检索到的相同盐值不同
- android - 尝试通过列表视图显示数据时应用程序崩溃
- php - 像其他变量一样在 PHP 中发送的数组(对于每个索引)