简体   繁体   English

从javascript获取数据属性

[英]Getting a data attribute from a javascript

I am attempting to insert a url into the data-url using javascript, and I am getting nowhere since I have no clue what I am supposed to do我正在尝试使用 javascript 将一个 url 插入到数据 url 中,但我无处可去,因为我不知道我应该做什么

Here is my html example这是我的 html 示例

<a class="button" data-url="http://www.google.com" href="#"></a>

all I have at the moment is within my javascript the following:我目前所有的内容都在我的 javascript 中:

var link = {
    url: 'http:www.google.com'
  }

but now I don't know how to get link to be pushed inside the data-url="".但现在我不知道如何将链接推送到 data-url="" 中。

All help is much appreciated.非常感谢所有帮助。

Use getAttribute just like you would any other attribute:像使用任何其他属性一样使用getAttribute

var url = document.querySelector('a.button').getAttribute('data-url');

Before going down that route, though, I hope you've carefully considered storing the url in the href attribute instead, which will - depending on your use case - probably be preferable in terms of graceful degradation.但是,在沿着这条路线前进之前,我希望您已经仔细考虑过将 url 存储在href属性中,这将 - 根据您的用例 - 在优雅降级方面可能更可取。

您还可以使用像document.querySelector('a.button').dataset.url这样的数据集

You can use attributes property of element.您可以使用元素的attributes属性。

 var data = $('[class="button"]')[0].attributes[1].value; console.log(data);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a class="button" data-url="http://www.google.com" href="#"></a>

Hi all many thanks to your input, it enlightened me as in how to complete this.大家好,非常感谢您的意见,它启发了我如何完成这项工作。

I did the following:我做了以下事情:

    var link = {
      url: 'http://www.google.com'
    };

    var el = document.querySelectorAll('a.button');

  el.forEach(element => {
    element.setAttribute('data-url', link.url);
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM