最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

I have a javascript snippet that goes:

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

It turns this into the html

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

I would like to add with javascript data-no-turbolink = true to the link so that i have in html

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

I tried

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

but it does not work.

How to do this ?

I have a javascript snippet that goes:

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

It turns this into the html

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

I would like to add with javascript data-no-turbolink = true to the link so that i have in html

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

I tried

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

but it does not work.

How to do this ?

Share Improve this question asked May 2, 2016 at 18:02 MathieuMathieu 4,80713 gold badges64 silver badges126 bronze badges 8
  • If I'm not mistaken you're using rails...? – Carl Edwards Commented May 2, 2016 at 18:07
  • Why not use: :link_to? – Carl Edwards Commented May 2, 2016 at 18:08
  • 2 If you want pure javascript what's with the jquery tag? – Paul Abbott Commented May 2, 2016 at 18:09
  • the link is not in the standard rails view but is inside a javascript modal: action: function(){ location.href = '<%= route_path %>'; } , as I'm using hubspot messenger: github.hubspot./messenger – Mathieu Commented May 2, 2016 at 18:09
  • Figure out how to get the anchor, then figure out how to set an attribute, or search MDN for dataset, and you should be set. – adeneo Commented May 2, 2016 at 18:10
 |  Show 3 more ments

2 Answers 2

Reset to default 4
location.setAttribute('data-no-turbolink', true) 

should do the trick. Dom API setAttribute

If you really need to do this via Javascript and assuming that there's an anchor element present on the page:

<%= 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");
  });
});

Though you can easily do this right in your rails template:

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

评论列表(0)

  1. 暂无评论