簡體   English   中英

Javascript:如何從2個不同文件中的特定文件中獲取變量的值?

[英]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文件。

如何動態加載JavaScript文件?

在每次迭代中,讀取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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM