【问题标题】:How to catch manual dropdown change, made by the user itself?如何捕获用户自己进行的手动下拉更改?
【发布时间】:2019-06-13 14:23:07
【问题描述】:

如何捕捉用户自己所做的下拉更改,而不是在加载页面并且为该下拉列表分配默认值时?

我尝试使用 e.originalEvent,但它不起作用。

$(self.options.selectChange).change(function (e){
   // check if the change event is a user-triggered event
   if (e.originalEvent) {
      ...
   }
});

我有一个有很多下拉菜单的表单,每个表单都有一个在页面加载时设置的默认值。该动作被认为是下拉,触发上面的代码,但我只想在用户手动更改选项时触发上面的代码。

我该怎么做?

【问题讨论】:

  • 嗨,看看我的回答,如果这对你没有帮助,可以提供一个工作示例,我会看看。 :)

标签: javascript jquery select onchange


【解决方案1】:

您正在搜索event.isTrigger

$('select').change(function(e) {
  console.log(e.isTrigger ? 'triggered' : 'manual')
})

$('button').click(function(e) {
  $('select').trigger('change')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select>
  <option>a</option>
  <option>b</option>
</select>

<button>Trigger</button>

【讨论】:

    【解决方案2】:

    我认为更好的方法是标记您的处理程序。使用label 参数创建自定义函数。

    const customHandler = (label) => {
    
      if (typeof label !== 'string') {
        label = 'defaultLabel';
      }
    
      return (jQueryEvent, customData) => {
    
        let customLabel = customData ? customData.name : label;
        let jqElem = $(jQueryEvent.currentTarget);
    
        // you can use IF statements here based on your customLabel value
    
        console.log('this element was triggered by', customLabel);
    
      }
    
    }
    
    $("select").on('change', customHandler('changedByUser'));
    
    const customTrigger = (label) => () => {
    
      $("select").trigger('change', {
        name: label || 'pageload'
      })
    
    }
    
    window.onload = customTrigger();
    setTimeout(customTrigger('this-timeout'), 2000)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select>
      <option>option 1</option>
      <option>option 2</option>
      <option>option 3</option>
      <option>option 4</option>
    </select>
    
    <br />
    <div id="output"></div>

    【讨论】:

    • 感谢您的回答。即使是几行代码,它也可以作为上述答案。
    猜你喜欢
    • 2017-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多