Javascript 获取脚本标签的数据属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14904378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:16:57  来源:igfitidea点击:

Get data attribute of script tag?

javascript

提问by Shpigford

Say I've got the following script tag:

假设我有以下脚本标签:

<script async data-id="p3PkBtuA" src="//example.com/embed.js"></script>

Within that embed.jsfile, how can I get the value of data-idattribute?

在该embed.js文件中,如何获取data-id属性值?

I'm trying to keep the embed.jsfile as light as possible, so ideally it wouldn't need to use some sort of javascript library.

我试图使embed.js文件尽可能轻巧,因此理想情况下它不需要使用某种 javascript 库。

回答by brice

For modern browsers that support html5 you can use document.currentScriptto get the current script element.

对于支持 html5 的现代浏览器,您可以使用它document.currentScript来获取当前脚本元素。

Otherwise, use querySelector()to select your script element by idor attribute.

否则,使用idattributequerySelector()来选择您的脚本元素。

Note that we don't use the srcattribute because that can be fragile if you're delivering over a CDN or with differences between development and production environments.

请注意,我们不使用该src属性,因为如果您通过 CDN 或开发环境和生产环境之间存在差异,则该属性可能很脆弱。

embed.js

嵌入.js

(function(){
    // We look for:
    //  A `script` element
    //  With a `data-id` attribute
    //  And a `data-name` attribute equal to "MyUniqueName"
    var me = document.querySelector('script[data-id][data-name="MyUniqueName"]');
    var id = me.getAttribute('data-id');
})();

In the host html:

在主机 html 中:

<script async 
  data-id="p3PkBtuA" 
  data-name="MyUniqueName" 
  src="//example.com/embed.js">
</script>

This approcah has the downside that you couldn't successfully embed two identical scripts. This is a pretty rare case, but could happen.

这种方法的缺点是您无法成功嵌入两个相同的脚本。这是一个非常罕见的情况,但可能会发生。

Note that I would personally us data-idto select the script instead of passing data, and would place the unique data in a more descriptive tag:

请注意,我个人data-id会选择脚本而不是传递数据,并将唯一数据放置在更具描述性的标签中:

<script async 
  data-id="MyUniqueName" 
  data-token="p3PkBtuA" 
  src="//example.com/embed.js">
</script>

which would let me use this following:

这将让我使用以下内容:

var token = document
  .querySelector('script[data-id="MyUniqueName"][data-token]')
  .getAttribute('data-token');

回答by rgthree

That embed.jsis being rendered in the DOM, so you have full access to it. Eithergive it an idand use document.getElementByIdof querySelctorAllor getElementsByTagName

embed.js在 DOM 中呈现,因此您可以完全访问它。Eithergive它的id和使用document.getElementByIdquerySelctorAllgetElementsByTagName

Within your embed.jsyou could have something like:

在您的内部,您embed.js可能有以下内容:

  var scripts = document.getElementsByTagName('script');
  for(var i = 0, l = scripts.length; i < l; i++){
    if(scripts[i].src === '//example.com/embed.js'){
      alert(scripts[i].getAttribute('data-id'));
      break;
    }
  }

You get the idea

你明白了

回答by Darin Dimitrov

Within that embed.js file, how can I get the value of data-id attribute?

在该 embed.js 文件中,如何获取 data-id 属性的值?

You will have to parse the DOM and look for the corresponding <script>tag and then fetch the attributes from it. Take a look at the document.getElementsByTagNamewhich would allow you to retrieve all <script>elements on the current page. Then loop through the result array returned by this method, match the correct script element using the srcattribute and then read the other attributes you are interested in.

您必须解析 DOM 并查找相应的<script>标签,然后从中获取属性。看看document.getElementsByTagName哪个允许您检索<script>当前页面上的所有元素。然后循环遍历此方法返回的结果数组,使用该src属性匹配正确的脚本元素,然后读取您感兴趣的其他属性。

var scripts = document.getElementsByTagName('script');
for (var i = 0; i < scripts.length; i++) {
    var script = scripts[i];
    // you might consider using a regex here
    if (script.getAttribute('src') == '//example.com/embed.js') {
        // we've got a match
        var dataId = script.getAttribute('data-id');
    }
}

回答by yonatan

var attributeValue = Array.prototype.slice.apply(document.scripts).filter(
     function(script){
         return script.src.indexOf('script.source.com/big/') > -1;
     })[0].attributes["atrributeName"].value;

where script tag is <sript src="www.script.source.com/big/dud/baa.js" atrributeName="some value"><script>

脚本标签在哪里 <sript src="www.script.source.com/big/dud/baa.js" atrributeName="some value"><script>

回答by Vitalii

var scripts = document.getElementsByTagName('script'); // load into a variable all the scripts of the page
for (var i = 0; i < scripts.length; i++) { // parse all scripts
        var script = scripts[i];
        if (script.getAttribute('src') == '//example.com/embed.js') {
            alert(script.dataset.id); // Show only specified script
        }
    }