获取价值数据并根据每个链接进行更改?

时间:2019-07-12 05:56:35

标签: javascript

如何将“数据令牌”的值降低到“ ??????????????????”在脚本中。它随每个链接而变化吗? 例如:

  • “下载01”链接使用令牌:“ 1111”,

  • “下载02”链接使用令牌:“ 2222”,

  • “下载04”链接使用令牌:“ 444444”,

<a data-token="1111" href="https://example.com/download=12345">Download 01</a>
<a data-token="2222" href="https://example.com/download=123456">Download 02</a>
<a data-token="444444" href="https://example.com/download=123457">Download 04</a>
<script>
window.linkurl = {
token: '??????????????????',
domains: ``,
patterns: `download=`
};
(function() {
    function doHash(el, token) {
        el.href = 'https://example.com/full/?api='
            + token
            + '&url='+btoa(el.href)+'=&type=1';
        console.log(el.href);
    }

    var token = linkurl.token || '';
    var domains = linkurl.domains.split('\n') || [];
    domains.push('example.com');
    domains.push('www.example.com');
    domains.push(location.hostname);
    var patterns = linkurl.patterns.split('\n').filter(function(item) {return Boolean(item)}) || [];
    var aTags = document.querySelectorAll('a[href]:not([href^="javascript"]):not([onclick]):not([ng-click])');
    aTags.forEach(function(el) {
        if (domains.indexOf(el.hostname) === -1) {
            doHash(el, token);
            return;
        }
        patterns.forEach(function(pattern) {
            try {
                var regex = new RegExp(pattern);
                if(regex.test(el.href)) doHash(el, token);
            } catch (e) {console.log(e)}
        });
    });
})();
</script>

更新 链接:http://jsfiddle.net/Lu8shmco/

1 个答案:

答案 0 :(得分:1)

您可以使用Element.dataset属性,它提供对来自data-*前缀的自定义属性的读/写访问。

因此您可以使用

获得价值
el.dataset.token

window.linkurl = {
  token: '??????????????????',
  domains: ``,
  patterns: `download=`
};

function doHash(el) {
  el.href = 'https://example.com/full/?api=' +
    el.dataset.token +
    '&url=' + btoa(el.href) + '=&type=1';
  console.log(el.href);
}

var domains = linkurl.domains.split('\n') || [];
domains.push('example.com');
domains.push('www.example.com');
domains.push(location.hostname);
var patterns = linkurl.patterns.split('\n').filter(function(item) {
  return Boolean(item)
}) || [];
var aTags = document.querySelectorAll('a[href]:not([href^="javascript"]):not([onclick]):not([ng-click])');
aTags.forEach(function(el) {
  if (domains.indexOf(el.hostname) === -1) {
    doHash(el);
    return;
  }
  patterns.forEach(function(pattern) {
    try {
      var regex = new RegExp(pattern);
      if (regex.test(el.href)) doHash(el);
    } catch (e) {
      console.log(e)
    }
  });
});
<a data-token="1111" href="https://example.com/download=12345">Download 01</a>
<a data-token="2222" href="https://example.com/download=123456">Download 02</a>
<a data-token="444444" href="https://example.com/download=123457">Download 04</a>