[英]How do I determine which value has been called from an array, to use in another function?
[英]How do I get the current value of a button being called from an array to display something from another array?
試圖從數組中獲取當前正在被調用的按鈕的數值,這樣我就可以基於bNames數組號顯示另一個數組中的圖像和說明。
我似乎沒有工作。 嘗試根據bNames的數值獲取要顯示的圖像[i]和說明[i]。
var bNames = ["#button01","#button02","#button03"];
var images = ["image01.png","image02.png","image03.png"];
var descriptions = ["And a one","And a two", "And a three"];
for (var i=0; i<bNames.length; i++){
$(bNames[i]).click(function(e) {
$("#image").html("<img src=images/" + images[i] + " />");
$("#desc").html(descriptions[i]);
});
}
非常感謝任何幫助,謝謝!
這個問題描述了您遇到的問題 。 另請參閱JavaScript循環關閉以獲取更多信息。 本質上,您始終使用i
持有的最后一個值。
這樣的事情應該可以解決問題:
for (var i=0; i<bNames.length; i++) {
(function(index) {
$(bNames[index]).click(function(e) {
$("#image").html("<img src=images/" + images[index] + " />");
$("#desc").html(descriptions[index]);
});
})(i);
}
同樣從這個問題,您可以改為:
$.each(bNames, function(i, item) {
$(item).click(function(e) {
$("#image").html("<img src=images/" + images[i] + " />");
$("#desc").html(descriptions[i]);
});
});
注意:永遠不要在循環內定義函數...
您在HTML5的世界中是一場革命 ...使用數據屬性...這是解決方案...
HTML:
<button class="button" data-index="0">Button01</button>
<button class="button" data-index="1">Button02</button>
<button class="button" data-index="2">Button03</button>
<div id="image"></div>
<div id="desc"></div>
Javascript:
var images = ["image01.png","image02.png","image03.png"];
var descriptions = ["And a one","And a two", "And a three"];
$(".button").click(function(){
var i = $(this).data("index");
$("#image").html("<img src=images/" + images[i] + " />");
$("#desc").html(descriptions[i]);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.