我正在英特尔 XDK 中开发一个应用,并希望通过 javascript 设置精灵按钮的href
。
我试过:
-
document.getElementById('button').href
-
document.getElementById('button').src
通过 setAttribute
使用 jQuery ..
谁能告诉我应该怎么做才能在英特尔 XDK 中设置精灵按钮的 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[this.id].url;
});
}
arr[] 声明在文件顶部。arr[] 有更多的数据,但例如我只显示这个。
当我尝试在此代码中访问它时,它给了我一个Uncaught TypeError: Cannot read property 'url' of undefined anonymous function
我已经在.addEventListener
代码之外对此进行了测试,并且有效。
如何从此代码中访问arr[]
?
谢谢
编辑2:我已经找到了我的问题的解决方案。它与变量范围有关。通过调用this.id
而不是j
,我可以访问arr
数组中的正确元素。
document.getElementById('button').href
在上面的代码中,您尝试获取button
没有src
的sprite button
元素href
您可以使用单击事件使用以下代码转到其他页面的元素。
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
循环。您可以使用以下代码直接访问 url:
var arr = [{
"url": "http://www.example.com/"
}]
document.getElementById('button').addEventListener("click", function() {
window.location.href = arr[0].url;
});