我有1页从另一台服务器加载Js文件。它在电子商务商店中的每个产品的加载文件,其id在url中,见下面的结构。
产品1: http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/1/d/itemjs
产品2:
http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/2/d/itemjs
产品3:
http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/3/d/itemjs
所有Js文件都包含如下代码
var MyItemData={"counts":{"q":1,"a":1,"r":2,"ar":4,"rr":0,"dq":1,"da":1,"c":0,"sdsd":0},"active":true};
现在我正在Html中读取此数据,如下所示
var mycounta = MyItemData.counts.a;
var mycountq = MyItemData.counts.q;
var mycountr = MyItemData.counts.r;
这里的问题是我只能获取最后一个产品的数据,因为变量MyItemData
对于所有文件都是相同的。我已经按ID读取了每个文件,但我不知道实现它的正确方法。有人试过这样的事吗?
答案 0 :(得分:1)
前提是您使用script
标记加载这些文件。您可以创建一个数组来保存项目,并使用内联脚本混合脚本标记,以便在数组中保存MyItemData
的当前值。
<script>
var items = [],
addItem = function() {
items.push(MyItemData)
};
</script>
然后在每个脚本之后调用addItem
或使用onload
事件进行游戏(不确定后者是否有效)。
<script
src="http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/1/d/itemjs"
>
</script>
<script>addItem()</script>
<script
src="http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/2/d/itemjs"
>
</script>
<script>addItem()</script>
等
答案 1 :(得分:1)
您可以循环下面的答案,动态加载外部js文件。
How do I load a javascript file dynamically?
在每次迭代中,阅读MyItemData
并使用它。
在上面的链接上使用功能loadJS
;
<script type="application/javascript">
var listOfJSFiles=["http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/1/d/itemjs", "http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/2/d/itemjs", "http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/3/d/itemjs"];
var listOfMyItemData=[];
function loadJS(file) {
// DOM: Create the script element
var jsElm = document.createElement("script");
// set the type attribute
jsElm.type = "application/javascript";
// make the script element load file
jsElm.src = file;
// finally insert the element to the body element in order to load the script
document.body.appendChild(jsElm);
}
var arrayLength = listOfJSFiles.length;
for (var i = 0; i < arrayLength; i++) {
loadJS(listOfJSFiles[i]);
listOfMyItemData.push(MyItemData);
//removing listOfJSFiles[i] from html is recommended.
}
</script>