脚本标记中的自定义属性

ton*_*jac 4 html javascript

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

<script type="text/javascript" mycustomattribute="foo">
    //javascript
</script>
Run Code Online (Sandbox Code Playgroud)

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

T.J*_*der 8

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

是的,使用data-*属性:

<script data-info="the information"...
Run Code Online (Sandbox Code Playgroud)

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

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

var info = document.getElementById("theId").getAttribute("data-info");
Run Code Online (Sandbox Code Playgroud)

否则,您必须对脚本标记进行假设.如果它始终位于页面的标记中(以后不使用代码添加),则可以执行以下操作:

var scripts = document.getElementsByTagName("script");
var info = scripts[scripts.length - 1].getAttribute("data-info");
Run Code Online (Sandbox Code Playgroud)

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

这是一个完整的例子: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>
Run Code Online (Sandbox Code Playgroud)


Bar*_*mar 2

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

<script id="myscript" type="text/javascript" data-mycustomattribute="foo">
Run Code Online (Sandbox Code Playgroud)

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

document.getElementById("myscript").getAttribute("mycustomattribute")
Run Code Online (Sandbox Code Playgroud)

或使用datasetAPI

document.getElementById("myscript").dataset.mycustomattribute
Run Code Online (Sandbox Code Playgroud)

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