我有一个对象,我想循环创建元素。每个元素都应该有一个onclick
来更改另一个元素的文本(用于动态生成的下拉列表)。
const orders = {
INDEX: 'index',
REVERSE_INDEX: 'reverse index',
RANDOM: 'random',
SELECTION: 'selection order',
REVERSE_SELECTION: 'reverse selection order',
CURRENT_ORDER: 'current start order',
REVERSE_CURRENT_ORDER: 'reverse current start order',
ALPHABETICAL: 'alphabetical',
REVERSE_ALPHABETICAL: 'reverse alphabetical'
};
var ddc = document.getElementById("orderDropDownContent");
for (var key in orders) {
var ddMenuItem = document.createElement("p");
ddMenuItem.className = "dropdown-item";
ddMenuItem.onclick = function() {
document.getElementById("orderDropDown").innerText = orders[key];
};
ddMenuItem.innerText = orders[key];
ddc.appendChild(ddMenuItem);
}
HTML只是
<div class="dropdown">
<div id="orderDropDown" value="index" class="dropbtn">index</div>
<div id="orderDropDownContent" class="dropdown-content">
</div>
</div>
内部文本适用于每个元素,并且每个元素都有一个onclick,但是问题是onclick
函数从创建时起就没有使用orders[key]
的value,而是使用< [表达式 orders[key]
等于对象“反向字母顺序”中的最后一个值。如何在创建函数时使用字符串值创建函数。
var theText = '' + orders[key];
但是那没用。我觉得以前可能已经问过这个,但是我找不到重复的。