javascript 脚本标签中的自定义属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17769688/
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-10-27 09:32:40  来源:igfitidea点击:

custom attributes in a script tag

javascripthtml

提问by tonejac

Can I use a custom attribute in a scripttag such as:

我可以在script标签中使用自定义属性,例如:

<script type="text/javascript" mycustomattribute="foo">
    // JavaScript
</script>

And then use the contained JavaScript to access the value of mycustomattribute?

然后使用包含的 JavaScript 访问mycustomattribute?

回答by T.J. Crowder

Can I use a custom attribute in a script tag such as:

我可以在脚本标签中使用自定义属性,例如:

Yes, using data-*attributes:

是的,使用data-*属性

<script data-info="the information"...

And then use the contained javascript to access the value of 'mycustomattribute'?

然后使用包含的 javascript 访问 'mycustomattribute' 的值?

Yes, probably. If you give the scripttag an id, you can do it reliably:

应该是。如果你给script标签一个id,你可以可靠地做到:

var info = document.getElementById("theId").getAttribute("data-info");

Otherwise, you have to make assumptions about the script tag. If it's always in the markup of the page (not added later using code), you can do this:

否则,您必须对脚本标记做出假设。如果它总是在页面的标记中(以后没有使用代码添加),你可以这样做:

var scripts = document.getElementsByTagName("script");
var info = scripts[scripts.length - 1].getAttribute("data-info");

That's because if the script tag is in the markup, it's run as soon as it's encountered (unless asyncor deferis used [and supported by the browser]), and will always be the last script tag on the page (at that point in time). But again, if code adds the script tag later, using createElementand appendChildor similar, you can't rely on that.

这是因为如果 script 标签在标记中,它会在遇到它时立即运行(除非asyncdefer被使用[并被浏览器支持]),并且将始终是页面上的最后一个脚本标签(在那个时间点) . 但同样,如果代码稍后添加脚本标签,使用createElementappendChild或类似的,你不能依赖它。

Here's a complete example: Live Copy

这是一个完整的示例:Live Copy

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Data on Script Tags</title>
</head>
<body>
  <script>
    function display(msg) {
      var p = document.createElement('p');
      p.innerHTML = String(msg);
      document.body.appendChild(p);
    }
  </script>
  <script data-info="first">
    (function() {
      var scripts = document.getElementsByTagName("script");
      var info = scripts[scripts.length - 1].getAttribute("data-info");
      display("Got info '" + info + "'");
    })();
  </script>
  <script data-info="second">
    (function() {
      var scripts = document.getElementsByTagName("script");
      var info = scripts[scripts.length - 1].getAttribute("data-info");
      display("Got info '" + info + "'");
    })();
  </script>
</body>
</html>

回答by TGH

You should be able to get it using jquery

您应该可以使用 jquery 获取它

$("script").attr("mycustomattribute");

Or try this using regular JavaScript

或使用常规 JavaScript 尝试此操作

document.getElementsByTagName("script")[0].getAttribute("mycustomattribute");

Might bake sense to give a script tag an id to be able to do this

给脚本标签一个 id 以便能够做到这一点可能很有意义

document.getElementById("someId").getAttribute("mycustomattribute");

回答by Barmar

Yes, you can do this. Browsers are required to ignore attributes they don't recognize in any tag (to allow for graceful degradation when a document uses new features with an old browser). However, it would be better to use a dataset tag, since these are explicitly reserved for users, so they don't conflict with future HTML changes.

是的,你可以这样做。浏览器需要忽略它们在任何标签中无法识别的属性(当文档使用旧浏览器的新功能时允许优雅降级)。但是,最好使用数据集标记,因为这些标记是明确为用户保留的,因此它们不会与未来的 HTML 更改发生冲突。

<script id="myscript" type="text/javascript" data-mycustomattribute="foo">

You can then access this either using an ordinary attribute accessor:

然后您可以使用普通属性访问器访问它:

document.getElementById("myscript").getAttribute("mycustomattribute")

or with the datasetAPI:

或使用datasetAPI

document.getElementById("myscript").dataset.mycustomattribute

(but see the browser compatibility table in the documentation).

(但请参阅文档中的浏览器兼容性表)。

回答by Vendetta

I built a libraryfor this very instance and it's quite easy to use:

我为此实例构建了一个,它非常易于使用:

<script id="your-library" src="./your-library.js" data-car="pagani" data-star-repo="yes, please :)">

and then you can get that data:

然后你可以得到这些数据:

/**
 * This returns the following:
 *
 * {
 *   car: 'pagani',
 *   starRepo: 'yes, please :)'
 * }
 */

 ScriptTagData.getData('your-library');


 /**
  * This returns the juust <script> tag
  */

 ScriptTagData.getData('your-library');

You can download it via Bower, CDN or just take the code: https://github.com/FarhadG/script-tag-data

您可以通过 Bower、CDN 下载或直接获取代码:https: //github.com/FarhadG/script-tag-data