我第一次使用本地存储,并在网上浏览一些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>
答案 0 :(得分:3)
我认为这是因为你正在使用变量&#34; i&#34;两次。在内部for循环中,尝试使用&#34; j&#34;代替:
for(var j = 0; j < buttons.length; j++){
buttons[j].addEventListener('click',remove);
}
编辑:事实上,您可以完全删除内部循环,只需执行:
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');
buttons[i].addEventListener('click',remove);
}
}