javascript - 通过从 DOM 读取值来添加数据属性
问题描述
我有以下 html 结构,我正在尝试获取 h 标签的文本并在相应的标签中添加为 data- 属性:
<div class="content">
<div class="body">
<h1>foo</h1>
<p>para-test1</p>
<p>para-test2</p>
<div class="link">
<a href="#">anchor1</a>
<a href="#"">anchor2</a>
<a href="#">anchor3</a>
</div>
</div>
</div>
<div class="content">
<div class="body">
<h1>bar</h1>
<p>para-test3</p>
<div class="link">
<a href="#"">anchor4</a>
</div>
</div>
</div>
所以'foo'应该设置为锚1、2、3元素的数据属性值,'bar'应该设置为锚4的数据属性值。像这样:
<a data-custom="foo" href="#">anchor1</a>
<a data-custom="foo" href="#"">anchor2</a>
<a data-custom="foo" href="#">anchor3</a>
<a data-custom="bar" href="#">anchor4</a>
我试图迭代元素,但我在第二个循环中感到震惊。
$(".content .body").each(function() {
$(this).find(".link").attr("data-hN", $(this).next(":header").text());
});
解决方案
您的 HTML 中有两次额外的双引号。但是,修复这个问题和前面的 JQuery(这对于这样一个微不足道的任务来说是多余的),请参阅下面的内联评论:
// Loop over the links
document.querySelectorAll("div.link > a").forEach(function(item){
// Set the current link data-custom attribute to the nearest
// .body ancestor and the first heading element within that text
item.dataset.custom = item.closest(".body").querySelector(":first-child").textContent;
console.log(item);
});
<div class="content">
<div class="body">
<h1>foo</h1>
<p>para-test1</p>
<p>para-test2</p>
<div class="link">
<a href="#">anchor1</a>
<a href="#">anchor2</a>
<a href="#">anchor3</a>
</div>
</div>
</div>
<div class="content">
<div class="body">
<h1>bar</h1>
<p>para-test3</p>
<div class="link">
<a href="#">anchor4</a>
</div>
</div>
</div>
推荐阅读
- java - 调整程序屏幕大小时如何缩放图像?
- algorithm - 改进用于计算相关性的 O(m+n) 算法?
- python - 使用 Tensorflow/PyTorch 加速自定义函数的最小化
- javascript - 如何在反应中使用相同的按钮允许位置权限和撤销权限?
- javascript - 滚动时jQuery淡出:视口边框上的元素闪烁
- c# - 尝试在 Naudio (c#) 中播放 ISampleProvider 时出现 NullReferenceException
- hugo - 如何通过文本编辑器嵌入代码?
- scala - 查找 Scala Array 深层文档?
- c++ - 如果我的类是文字类,那么将我的类的对象声明为 constexpr 是否多余?
- pandas - 阻止熊猫重命名具有相同名称的列,以便我可以使用宽到长