在悬停时获取选择框的值或在同一事件中更改

时间:2016-10-04 08:25:47

标签: javascript jquery html

抱歉英文不好。如果用户更改选择框或只悬停在包含单个事件的选择框上,如何获取选择框的值。我试过这个,但它不起作用

jQuery("select[name*=super_attribute]").on('change', function(){
 alert('trigger'); 
});

我知道我们可以做这样做单独的功能

jQuery("select[name*=super_attribute]").on('hover', function(){
 alert('trigger'); 
});

.css

但我想单独处理一个事件,因为我会在两种情况下都做同样的功能。

3 个答案:

答案 0 :(得分:1)

事件列表中不需要逗号,当您必须为多个选择器应用任何操作时使用逗号

jQuery("select[name*=super_attribute]").on('change mouseover', function(){
  alert('trigger'); 
});

如果您必须选择多个元素,则可以使用这样的逗号

jQuery("select[name*=super_attribute],#xyz").on('change mouseover', function(){
      alert('trigger'); 
    });

答案 1 :(得分:0)

删除事件名称之间的逗号, - 它们应仅用空格分隔。

jQuery("select[name*=super_attribute]").on('change mouseover', function(){
  alert($(this).val()); 
});

jQuery(document).ready(function() {
  jQuery("select[name*=super_attribute]").on('change mouseover', function() {
    console.clear();
    console.log($(this).val());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="super_attribute">
  <option>1</option>
  <option selected>2</option>
  <option>3</option>
</select>

答案 2 :(得分:0)

将元素绑定到多个事件有两种方法。

  1. 您可以使用.on()将函数绑定到多个事件。

    $('#yourelement').on('change mouseover keyup keypress blur', function(e) {
         alert('trigger'); 
    });
    
  2. 定义类似

    的函数
    var myFunction = function() {
      alert('trigger'); 
    }
    
  3. 并将myFunction作为参数传递给事件函数。

    $('#yourelement')
    .change(myFunction)
    .mouseover(myFunction)
    .keyup(myFunction)
    .keypress(myFunction)
    .blur(myFunction)
    

    注意:#yourelement是要绑定事件的元素的id。文档就绪后调用这些方法。

    在您的情况下,您可以使用     $(函数(){

        jQuery("select[name*=super_attribute]").on('change mouseover', function(){
         alert('trigger'); 
        });
    });
    

    或     $(函数(){         var myFunction = function(){               警报(&#39;触发&#39);             }

    $('select[name*=super_attribute]')
        .change(myFunction)
        .mouseover(myFunction);
    });