简体   繁体   English

jQuery .on()无法与多个选择器一起使用

[英]jQuery .on() not working with multiple selectors

I have a form and am using jQuery to listen for and record changes by the user. 我有一个表单,正在使用jQuery来侦听和记录用户的更改。 It works great for either input or select fields, but does not seem to like combining them. 它适用于输入或选择字段,但似乎不喜欢将它们组合在一起。 Per the jQuery documentation on the .on() function, the selector should be a string. 根据.on()函数上的jQuery文档,选择器应为字符串。 Looking around Stack Overflow, and it seems like 'select input' should work, but it is not. 环顾堆栈溢出,似乎“选择输入”应该起作用,但事实并非如此。 What is the correct way to use multiple selectors? 使用多个选择器的正确方法是什么?

Full fiddle: http://jsfiddle.net/L55rvuqh/4/ 完整提琴: http : //jsfiddle.net/L55rvuqh/4/

Code in question: 有问题的代码:

$('#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);
});

You should change it; 您应该更改它;

'select input'

to

'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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM