jquery onclick or onchange on different elements

jquery onclick or onchange on different elements

本文关键字:different elements on onchange onclick or jquery      更新时间:2023-09-26

我有一个选择菜单和两个箭头,用于更改选择值(+/-)。今天,我有一个点击箭头触发的功能,它会更新选择中的值,但如果有人直接在下拉列表中更改值(而不是使用箭头),我也想添加一个功能来执行同样的操作。

我可以重写相同的函数,只需将箭头的ID更改为select的ID,并将onclick更改为onchange,但这将是多余的。我更喜欢使用OR运算,并且只编写一次函数。

有没有办法在两个事件之间执行OR运算?

当前代码:

$(document).ready(function(){
   $('img[id*="downArrow"]').on("click", function(){
     //update the value in the select
   });
});   

我想实现的目标:

$(document).ready(function(){
    $('img[id*="downArrow"]',#idOfMySelect).on("click onchange", function(){
         //update the value in the select
    });
});  

您可以在选择器之间使用逗号而在事件之间不使用逗号来组合它们。

不过,您需要小心,因为您可能不想在单击select元素时触发该函数:

$('img[id*="downArrow"], #mySelect').on('click change', function(e) {
  if(e.type==='change' || this.id!=='mySelect') {
    alert('Success!');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="downArrow" src="http://placehold.it/50x50">
<select id="mySelect">
  <option>Option 1</option>
  <option>Option 2</option>
</select>

您正朝着正确的方向前进,只是键入了"change"而不是"onchange"

$(document).ready(function(){
    $('img[id*="downArrow"]',#idOfMySelect).on("click change", function(){
         //update the value in the select
    });
});  

您可以在两个侦听器上使用一个方法。示例:

function onEventFunction(e){
}
$(document).ready(function(){
   $('img[id*="downArrow"]').on("click change", onEventFunction);
});