我有这个下拉列表,其中有两个选项,蓝色和绿色。如果我选择蓝色,每当我点击文本输入字段时,它的背景就会在蓝色和黑色之间切换,这是文本字段的背景颜色。红色选项也是如此。但是,我只在第一次和第二次工作过的代码。从第三次开始,即使我选择红色,它也会在蓝色和另一种颜色之间切换。 这是我的 HTML:
谁知道哪里错了?我在想,也许我没有完全理解 jquery 的 change 函数是如何工作的。
$('#change_color').on('change', function() {
//get the text value of the option chosen
var colorOption = $("#change_color option:selected").text();
//if option chosen is red then allow change input box to red
if (colorOption === 'Red') {
$('.my-input').click(function(inputBox) {
$(inputBox.target).toggleClass('red');
});
}
//if option is chosen is red then allow change input box to blue
else {
$('.my-input').click(function(inputBox) {
$(inputBox.target).toggleClass('blue');
});
}
});
.my-input {
background-color: black;
width: 5%;
font-size: 3vw;
}
.red {
background-color: red;
width: 5%;
font-size: 3vw;
}
.blue {
background-color: blue;
width: 5%;
font-size: 3vw;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="change_color" class="form-control box-border" placeholder="SPECIAL CHAR">
<option selected disabled>Special Char</option>
<option>Red</option>
<option>Blue</option>
</select>
<input type="text" class="my-input">
<input type="text" class="my-input">
<input type="text" class="my-input">
最佳答案
当您执行 $(element).click(...)
时,您正在为该元素附加一个新的监听器。如果你重复这样做,那些听众就会堆积起来。在您的示例中,每次更改下拉菜单时,您都会添加一个新事件 - 不会替换之前的事件。
相反,最简单的方法可能是这样的:
有一个存储颜色的全局变量
将更改事件附加到您的下拉列表。更改时,将全局颜色变量设置为所选选项
将点击事件附加到您的输入。单击时,将背景设置为全局颜色变量
看起来像这样:
let backgroundColor; //Global var to hold color choice
$("#change_color").on("change", function() { //When <select> changes
backgroundColor = $(this).val(); //Update global var
}).change(); //Fire this event on page-load
$(".my-input").on("click", function() { //When input is clicked
$(this).toggleClass(backgroundColor); //Toggle class
});
.my-input { background-color: black; }
.blue { background-color: blue; }
.red { background-color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="change_color">
<option>blue</option>
<option>red</option>
</select>
<input class="my-input" />
<input class="my-input" />
<input class="my-input" />
关于javascript - 单击 javascript 时颜色不会正确更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58347896/