脚本标记中的自定义属性 [英] custom attributes in a script tag

查看:78
本文介绍了脚本标记中的自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

推荐答案


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

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

是的,使用 data - * attributes

Yes, using data-* attributes:

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




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

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

是,可能。如果你给脚本标记 id ,你可以可靠地做到:

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

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");

这是因为如果脚本标记在标记中,它会在遇到时立即运行(除非< a href =http://www.w3.org/TR/html5/scripting-1.html#attr-script-async =noreferrer> async 或者使用 defer [并且浏览器支持]),并且始终是页面上的最后一个脚本标记(在那个时间点)。但同样,如果代码添加脚本标记以后,则使用 createElement appendChild 或类似,你不能依赖它。

That's because if the script tag is in the markup, it's run as soon as it's encountered (unless async or defer is 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 createElement and appendChild or similar, you can't rely on that.

这是一个完整的例子:实时复制

Here's a complete example: 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>

这篇关于脚本标记中的自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆