我有一个很大的网站,大多数地方都有带图标的锚链接.当我点击图标时,它会将我们带到同一页面中的部分.因此,创建锚链接并用id值替换它们是一项大量的手动工作,所以我想使用简单的代码,而不是任何插件.

我用下面的示例代码说明了它.我希望这是self 解释.如果需要任何细节,我很乐意提供.JavaScript或PHP都可以.

<div class="" id="process-invoices">
  <a href="#{link-should-be-from-above-div-id}">My Icon, No text</a>
</div>
<div class="" id="plan-payments">
  <a href="#{link-should-be-from-above-div-id}">My Icon, No text</a>
</div>
<div class="" id="make-payments">
  <a href="#{link-should-be-from-above-div-id}">My Icon, No text</a>
</div>
<div class="" id="track-performance">
  <a href="#{link-should-be-from-above-div-id}">My Icon, No text</a>
</div>

我试过其他的例子,但没有得到结果.

推荐答案

可以,您可以 Select 所有div,然后在其中找到每个div的锚标记,并将其href属性设置为div的id.

// Select all divs
var divs = document.querySelectorAll('div');

// Loop through each div
divs.forEach(function(div) {
    // Get the id of the div
    var id = div.id;

    // Find the anchor tag inside the div
    var anchor = div.querySelector('a');

    // Set the href of the anchor tag to the id of the div
    anchor.href = '#' + id;
});

Javascript相关问答推荐

如何编辑代码FlipDown.js倒计时?

如何获取转换字节的所有8位?

使用json文件字符串来enum显示类型字符串无法按照计算的enum成员值的要求分配给类型号

使用useup时,React-Redux无法找到Redux上下文值

如何才能拥有在jQuery终端中执行命令的链接?

. NET中Unix时间转换为日期时间的奇怪行为

当点击注册页面上的注册按钮时,邮箱重复

将旋转的矩形zoom 到覆盖它所需的最小尺寸&S容器

还原器未正确更新状态

在SHINY R中的嵌套模块中,不能使用Java代码

更新Redux存储中的对象数组

在表单集中保存更改时删除';禁用';

在Odoo中如何以编程方式在POS中添加产品

将嵌套数组的元素乘以其深度,输出一个和

如何找到带有特定文本和测试ID的div?

如何将对象推送到firestore数组?

扩散运算符未按预期工作,引发语法错误

如何处理不带参数的redux thunk payloadCreator回调函数?

JSON Web令牌(JWT)错误:RSA密钥对的签名无效

如果未定义,如何添加全局变量