代码之家  ›  专栏  ›  技术社区  ›  user2242044

jQuery。on()不使用多个选择器

  •  0
  • user2242044  · 技术社区  · 7 年前

    我有一个表单,正在使用jQuery来监听和记录用户的更改。它对输入或选择字段都很有效,但似乎不喜欢将它们组合在一起。根据 .on() 函数,选择器应为字符串。看看堆栈溢出,似乎“选择输入”应该可以工作,但事实并非如此。使用多个选择器的正确方法是什么?

    全小提琴: 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);
    });
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Emre Kabaoglu    7 年前

    你应该改变它;

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