我有一个表单,正在使用 jQuery 来监听和记录用户的更改。它非常适合输入或选择字段,但似乎不喜欢将它们组合起来。根据关于 .on()
函数的 jQuery 文档,选择器应该是一个字符串。环顾堆栈溢出,似乎“选择输入”应该有效,但事实并非如此。使用多个选择器的正确方法是什么?
完整 fiddle : http://jsfiddle.net/L55rvuqh/4/
有问题的代码:
$('#test').on('focusin', 'select input', function(){
$(this).data('val', $(this).val());
}).on('change', 'select input', function(){
var prev = $(this).data('val');
var current = $(this).val();
console.log("Prev value: " + prev);
console.log("Current value: " + current);
});
最佳答案
你应该改变它;
'select input'
至
'select,input'
$('#myform').on('focusin', 'select,input', function(){
$(this).data('val', $(this).val());
}).on('change', 'select,input', function(){
var prev = $(this).data('val');
var current = $(this).val();
console.log("Prev value: " + prev);
console.log("Current value: " + current);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form id="myform">
<input id="field1" type="text" />
<select id="field2">
<option>1</option>
<option>2</option>
</select>
</form>
关于javascript - jQuery .on() 不适用于多个选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48359381/