我正在尝试做一个简单的任务。
代码如下。每当我运行它时,标签只会改变一次而选项标签永远不会改变。
$(document).ready(function() {
showButton();
});
function showButton() {
//draw button
var $button = '<button type="button" id= "button">Button</button>';
$('.div1').after(button);
//add event listener on click
document.getElementById("thebutton").addEventListener("click",showLabel());
}
function showLabel() {
var label = "one";
var option = document.getElementById("options").value;
if(option == "one") {
label = "one";
}
if(option == "two") {
label = "two";
}
if(option == "two") {
label = "three";
}
var selectOptions = '<div align ="right"><select id="options"><option value="one">one</option><option value="two">two</option><option value="three">three</option></select></div>';
document.getElementById("container").innerHTML = selectOptions+ label;
document.getElementById("options").addEventListener("change", function(){
console.log('changed option');
showLabel();
});
}
有什么想法吗?
答案 0 :(得分:0)
编辑:
<script>
$(document).ready(function() {
$('.div1').append('<button type="button" onclick="javascript:showLabel()" id="button">Button</button>');
$('.container').append('<div><select id="options"><option value="1">one</option><option value="2">two</option><option value="3">three</option></select></div>');
});
function showLabel() {
var option = document.getElementById("options").value;
if (option == 1) {
labelVal = 'one';
} else if (option == 2) {
labelVal = 'two';
} else if (option == 3) {
labelVal = 'three';
}
if (document.getElementById('label') != null) {
$('#label').val(labelVal);
} else {
$('.container').append('<input type="text" id="label" value="' + labelVal + '">');
}
}
</script>
<div class="div1"></div>
<div class="container"></div>