2015-10-14 65 views
0

我正在開發一個應用程序英特爾XDK並希望通過javascript設置一個精靈按鈕的href英特爾XDK:在精靈按鈕中設置href

我已經試過:

  • document.getElementById('button').href

  • document.getElementById('button').src

通過 setAttribute

使用jQuery ..

任何人誰可以告訴我,我應該做的設置一個精靈按鈕的href在intel XDK

編輯:

現在,我使用這個代碼:

var arr = [{ 
    "url": "http://www.example.com/" 
}] 

for(j =0; j < arr.length; j++){ 

    document.getElementById('button').addEventListener("click", function() { 
         window.location.href = arr[this.id].url;     
        }); 
} 

ARR的[]聲明該文件的頂部。 arr []有更多的數據,但是例如我只顯示這個。

當我嘗試訪問它在此代碼它給我一個Uncaught TypeError: Cannot read property 'url' of undefined anonymous function

我已在.addEventListener代碼之外進行了測試,工程。

如何從此代碼中訪問arr[]

謝謝

編輯2:我找到了我的問題的解決方案。它與變量範圍有關。通過調用this.id而不是j我可以訪問arr陣列中的正確元素。

回答

0
document.getElementById('button').href 

在上面的代碼中,你試圖讓button元素是sprite button不具有可以使用單擊事件中使用下面的代碼去其他頁srchref元素。

var myLinkArray = [{"id":"1","url":"www.example.com"}] 
document.getElementById('button').addEventListener("click", function() { 
window.location.href = myLinkArray[0].url; 
}); 

您水溼直接傳遞參數點擊事件,但可以使用點擊事件函數中定義的數組。

此代碼爲click事件添加事件偵聽器,並重定向到給定的href

var arr = [{ 
    "url": "http://www.example.com/" 
}] 
for(j =0; j < arr.length; j++){ 
    document.getElementById('button').addEventListener("click", function() { 
         window.location.href = arr[j].url; 
    }); 
} 

沒有必要使用for循環。您可以使用以下代碼直接訪問網址:

var arr = [{ 
    "url": "http://www.example.com/" 
}] 
document.getElementById('button').addEventListener("click", function() { 
    window.location.href = arr[0].url; 
}); 
+0

感謝您的回覆。這個解決方案確實工作,但是我想傳遞一個數組,我想從中獲取url並將其設置爲href。但它不斷給我一個錯誤,說它無法識別數組。 document.getElementById('button')。addEventListener(「click」,function(arr){window.location.href = arr [j] .getlink; }); – RSSD

+0

你能告訴我數組的值是多少?它在哪裏定義? –

+0

這是一個數組,它充滿了json數據。所以數組看起來像[{「id」:「1」,「url」:「www.example.com」}] – RSSD