1
我第一次使用本地存储并在线浏览一些JS教程,因为我很生锈。制作一本字典,你可以在2个成语中添加单词,然后显示。除了对象“dict”中的第二项之外,一切工作正常,虽然它在对象中,但并未显示。它显示在控制台输出中。可能是循环中的索引。虽然看不到它。任何灯光棚将不胜感激。对象属性在循环中丢失
function getDictionary(){
var dict = {},
dictStr = localStorage.getItem('dictionary');
if(dictStr !== null){
dict = JSON.parse(dictStr);
}
return dict;
}
function show(){
var html = "";
var resultOutput = document.getElementById("resultOutput");
var dict = getDictionary();
for(var i = 0; i < Object.keys(dict).length; i++){
key = Object.keys(dict)[i];
html += "<p class='normal-paragraph'>The english word <span style='color: green'> " + key +
" </span>in portuguese is <span style='color: green'> " + dict[key]+
"</span> <button class='removeBtn' id='"+ i +"' >x</button></p>";
resultOutput.innerHTML = html;
var buttons = document.getElementsByClassName('removeBtn');
for(var i = 0; i < buttons.length; i++){
buttons[i].addEventListener('click',remove);
}
}
console.log("");
console.log("All words: "+ JSON.stringify(dict));
}
HTML ...
<p id="sayHello"></p>
<fieldset id="translateField">
<legend> Translate english to Portuguese</legend>
<input type="text" id="newWordEng" name="newWordEng" value="" placeholder=" write the english word" >
<input type="text" id="newWordPt" name="newWordPt" value="" placeholder=" write the portuguese word">
<input type="button" id="addWordBtn" name="addWordBtn" value="Add New Word">
</form>
</fieldset>
<div id="resultOutput">
</div>
<script src="src/translate.js"></script>
</body>
实际上是纽襻可能需要被移出其他循环 – charlietfl
是的,我不认为额外的循环甚至是必要的。我编辑了我的答案来解释这一点。 –
也想知道,但我们不知道长度是否相同 – charlietfl