javascript - 如何为两个元素设置一个事件处理程序?

标签 javascript jquery html select event-handling

目前第二个元素只会在第一个元素之后发生变化。

是否可以在两个元素上使用相同的事件处理程序,如果它们都是下拉框并且在构建正确的 URL 时保持两个元素被选中,无论哪个元素接收到事件?

$(function(){
   var url = '';
    $('#search_region').change(function () {
        url = $(this).val();
        window.location.hash = url;
         console.log(window.location.hash);
    });

    $('#search_categories').change(function () {
       if(url !==''){
         window.location.hash = url+"&"+$(this).val();
       }
        console.log(window.location.hash);
    });

});

最佳答案

At the moment the second element is only ever changed after the first one is.

在这种情况下,您可以类别的哈希值添加到区域

$('#search_region, #search_categories').change(function () {
   var regURL =  $('#search_region').val();    
   var catURL =  $('#search_categories').val();    

   window.location.hash += regURL + ( catURL ? ("&" + catURL) : "" );
   console.log(window.location.hash);
});

关于javascript - 如何为两个元素设置一个事件处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48623369/

相关文章:

javascript - 当 Canvas 全屏时,如何获取 HTML5 Canvas 上的鼠标位置?

php - 如何将时间选择器添加到jquery jtable?

html - 复选框占宽度的 100%

javascript - 具有 onclick 事件的 HTML anchor 链接仅有效一次

html - 在 CSS 中对齐下拉菜单

JavaScript 将数组从循环追加到数组

javascript - 图片上传预览文件路径

javascript - 使用嵌入的 javascript 将 cookie 读入 Shiny 应用程序

javascript - 如何按后退按钮隐藏叠加层

javascript - Highcharts 散点图图例切换运行缓慢