添加数据属性及其值以使用纯javascript进行链接

Add data-attribute and its value to link with pure javascript

本文关键字:javascript 链接 数据属性 添加      更新时间:2023-09-26

我有一个javascript片段,它是:

function(){
   location.href = '<%= my_route %>';
}

它将其转换为html

<a href="myroute">a certain text i have no problem here</a>

我想在链接中添加javascript数据no turbulink=true,这样我就可以在html中使用了

<a href="myroute"  data-no-turbolink = true >a certain text i have no problem here</a>

我试过

function(){
   location.href = '<%= my_route %>' location.data-no-turbolink = true;
}

但它不起作用。

如何做到这一点?

location.setAttribute('data-no-turbolink', true) 

应该做到这一点。Dom API设置属性

如果您真的需要通过Javascript并假设页面上有一个锚元素:

<%= link_to "Example Link", example_path, { class: "example-link" } %>

document.addEventListener("DOMContentLoaded", function() {
  var exampleLinks = document.getElementsByClassName("example-link");
  Array.prototype.forEach.call(exampleLinks, function(elem, index) {
      elem.setAttribute("data-no-turbolink", "true");
  });
});

尽管你可以很容易地在你的rails模板中做到这一点:

<%= link_to "Example Link", example_path, { data: { "data-no-turbolink": true } } %>