0

我有一个像这样嵌入的脚本“myscript.js”:

<script type="text/javascript" src="myscript.js" data-param="{'param1':true,'param2':false}"></script>

如何获取data-parammyscript.js 内部的值?我宁愿在没有 jQuery 的情况下这样做。

PS。我曾经看到过这样的事情:<script src="myscript.js,param3">-param3如果我这样做,我会怎样?

4

2 回答 2

1

就像是:

var param = document.getElementsByTagName("script")[0].getAttribute("data-param");

这假设您只有 1 个脚本(因此是[0])——如果您有更多,那么您将不得不循环并获得正确的值。

于 2013-10-29T13:44:34.260 回答
0

Get the last script element in the page and use getAttribute to get the parameters. The last script element is always the current one, so you don't need to work with IDs.

// Get all script tags
var scriptElements = document.getElementsByTagName("script");
// Get the number of scripts
var numberOfScripts = scriptElements.length;
// The current script is the last script in the list
var currentScript = scriptElements[numberOfScripts - 1];
// Now you can retrieve the attribute
var param = JSON.parse(currentScript.getAttribute("data-param"));

This is the same, only shorter and less readable:

var scriptElements = document.getElementsByTagName("script");
var param = JSON.parse(scriptElements[scriptElements.length - 1].getAttribute("data-param"));
于 2013-10-29T13:51:48.570 回答