我正在尝试使用 jquery 对 <input>
事件做出反应,以便在输入包含文本时立即修改背景标签:
$('#inpt').on('input', ':text', function() {
Window.alert("test");
$('#mytext').attr('background', 'red');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<input id="inpt" type="text" placeholder="Type in here" />
</div>
<span id="mytext" style="background:green">Test</span>
结果:没有任何反应。我什至没有收到警报。为什么?
答案 0 :(得分:1)
在函数内部使用选择器的问题是 $('#inpt') 是查找选择器的容器。但是在这种情况下,容器也是您在 on() 函数中定义的选择器 (:input),然后它不起作用,并且 Window 也输入错误。
attr 用于更新元素的属性,背景不包含在 attr 列表中。然后你应该包装背景:red inside style attr 或使用 css({background:red})
$('#inpt').on('input', function() {
window.alert("test");
$('#mytext').attr('style', 'background:red');
});
答案 1 :(得分:0)
你应该使用 document 和 keyup
$(document).on('keyup', '#inpt', function() {
alert("test");
$('#mytext').css({'background': 'red'});
});