![](/img/trans.png)
[英]HTML JavaScript, how would I be able to make this function work using JavaScript by giving each element a different Id
[英]Giving a different id to each child of an element
有史以來第一個問題,對編程來說是新的。 我會盡量簡潔。
我想做的是在選定的div內創建一堆孩子,並為每個孩子提供特定的html內容(來自預定義的數組),並為每個孩子提供不同的id。
我為此創建了一個循環:
Game.showOptions = function() {
var i = 0;
Game.choiceElement.html("");
for (i=0; i<Game.event[Game.state].options.length; i++) {
Game.choiceElement.append(Game.event[Game.state].options[i].response);
Game.choiceElement.children()[i].attr("id","choice1");
}
};
使用數組的預定義值:
Game.event[0] = { text: "Hello, welcome.",
options: [{response: "<a><p>1. Um, hello...</p></a>"},
{response: "<a><p>2. How are you?</p></a>"}]
};
該方法似乎不起作用,因為循環僅在一次迭代后停止運行。 我真不知道為什么。 如果有一種完全不同的方式來獲取我所需要的東西,那么我會不知所措。
如果我在數組中定義每個p的id屬性,它可以工作,但是我想避免這種情況。
這個想法是為對話選擇(基於文本的rpg樣式)創建一個功能齊全的算法,該算法可以與預定義的數組一起使用。
提前致謝。
我認為您的循環問題可能在幾個不同的地方。 這是您應該檢查的三件事,我假設您有,但沒有給我們看...
Game
是否定義為對象?
var Game = {};
event
定義為數組嗎?
Game.event = new Array();
Game.state
是否返回一個數字,以及那個數字? 我想這比我在這里寫的要動態得多,但是希望您能理解。
Game.state = 0;
現在,假設以上所有功能均正常運行...
使用eq(i)
代替[i]
。
for (var i = 0; i<Game.event[Game.state].options.length; i++) {
Game.choiceElement.append(Game.event[Game.state].options[i].response);
Game.choiceElement.children().eq(i).attr("id","choice" + (i + 1));
}
這是JSFiddle 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.