[英]Javascript : How to get value of variable from specific file from 2 different file?
我有一页从另一台服务器加载Js文件。 电子商务商店中每个产品的加载文件及其url中的ID,请参见以下结构。
产品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读取每个文件,但我不知道实现它的正确方法。 有没有人尝试过这样的事情?
前提是您正在使用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>
等等
您可以循环下面的答案,以动态加载外部js文件。
在每次迭代中,读取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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.