gpt4 book ai didi

javascript - 对象属性在循环中丢失

转载 作者:行者123 更新时间:2023-11-30 11:49:47 25 4
gpt4 key购买 nike

我是第一次使用本地存储,因为我很生疏,所以在线学习了一些 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>

最佳答案

我认为这是因为您使用了变量“i”两次。在内部 for 循环中,尝试改用“j”:

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);
}
}

关于javascript - 对象属性在循环中丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39822120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com