想法是这样的:当我点击“word1”(或“word2”)时,选择标签会显示选项。单击其中一个选项后,我的脚本会更改“word1”(或“word2”)选项。我可以更新选项,但是一旦我点击其中一个选项,脚本总是会写入最后一个选项。 该脚本为所有选项写入相同的 onClick 属性... 我一直在寻找很多,但我不明白为什么会发生,以及如何解决它。
代码如下:
function updatemyselect(currentElement, optionsList) {
var mySelect = document.getElementById("mySelect");
var i;
//Clear the options
mySelect.options.length = 0;
//Add the options
for (i = 0; i < optionsList.length; i++) {
var option = document.createElement("option");
var newWord = optionsList[i]
option.text = newWord;
option.onclick = function() {
currentElement.innerHTML = newWord;
};
mySelect.add(option);
}
}
<select id="mySelect">
</select>
<p onclick="updatemyselect(this,['Dog','Cat','Fish'])" class="changedWord">Word1</p>
<p onclick="updatemyselect(this,['Cow','Horse','Whale'])" class="changedWord">Word2</p>
提前致谢
最佳答案
您不能在“选择框”的“选项”属性上绑定(bind)“点击事件”。您需要在“选择元素”上绑定(bind)一个 onchange 事件监听器。在更改事件监听器的回调函数中放置用于更新单词文本的代码逻辑。由于 'change' 事件监听器不在 'updatemyselect' 函数的范围内,您可以将最后单击的元素存储在变量中,并在回调函数中使用相同的变量来更新所需的单词文本。请引用我编辑的以下代码。
var clickedElement;
function updatemyselect(currentElement, optionsList) {
clickedElement = currentElement;
var mySelect = document.getElementById("mySelect");
var i;
//Clear the options
mySelect.options.length = 0;
//Add the options
for (i = 0; i < optionsList.length; i++) {
var option = document.createElement("option");
var newWord = optionsList[i]
option.text = newWord;
/*option.onclick = function() {
currentElement.innerHTML = newWord;
};*/
mySelect.add(option);
}
}
document.getElementById("mySelect").addEventListener("change", updatePTag);
function updatePTag(){
clickedElement.innerHTML = this.value;
};
<select id="mySelect">
</select>
<p onclick="updatemyselect(this,['Dog','Cat','Fish'])" class="changedWord">Word1</p>
<p onclick="updatemyselect(this,['Cow','Horse','Whale'])" class="changedWord">Word2</p>
关于javascript - 创建选项 onClick 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28699439/