如果输入值动态变化,有什么方法可以触发“更改”事件侦听器吗?

问题描述 投票:0回答:2

假设,我有一个 deleerated 输入字段,其类名“bulk_number”位于父类名称“all_bulk_inputs”内,还有一个按钮,每当我单击它时,该按钮都会向该输入字段添加随机数。现在我想在数字发生变化时触发 change 事件侦听器。

例如:

   <!-- input field under all_bulk_inputs -->
   <div class="all_bulk_inputs">
      <input class="bulk_number" name="rand_number" />  <!-- dynamically added under the 'all_bulk_inputs' parent -->
   </div>

   <button id="add_rand">Add Random Number</button>

   <script>
       $('#add_rand').on('click', function(){
           $('.bulk_number').val(10) //suppose, 10 is my random number
            

           //what I want is forcefully trigger on change like bellow, if possible
           $('.all_bulk_inputs').trigger('change', 'bulk_number', function(){
               console.log('bulk number changed)
           })
       })

   </script>
javascript html jquery addeventlistener delegated-properties
2个回答
1
投票

首先,行日志中有错误。有几种方法可以做到这一点,但这是最简单的一种,我已经解释了带注释的代码是什么

console.log('批量号码改变)

那么您可能想检查变更文件变更

          <!DOCTYPE html>
          <html>

          <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
          </head>

          <body>
            <div class="all_bulk_inputs">
              <input class="bulk_number" name="rand_number" /> <!-- dynamically added under the 'all_bulk_inputs' parent -->
            </div>
            <button id="add_rand">Add Random Number</button>
            <script>
              $(document).ready(function() {
                //When random number setted to the input under all_bulk_inputs div below will triggered
                $('.all_bulk_inputs .bulk_number').on('change', function() {
                  console.log(`bulk number changed and the value is ${$(this).val()}`)
                })
                $('#add_rand').on('click', function() {
                  // create between 0 and 100 number and set to input
                  const rnd = Math.floor(Math.random() * 100)
                  $('.bulk_number').val(rnd).change()
                })
              });
            </script>
          </body>

          </html>

0
投票

随机遇到这个问题,因为这是谷歌的热门结果,决定为后代回答它:

虽然我对这个示例中触发更改事件的行为提出质疑,但它添加了更多处理逻辑,而我们可以只调用事件解析的任何逻辑,另一个问题的答案提供了关于如何创建事件的全面解释激发我们的投入。

因此,在这种情况下,我们可以通过以下方式使用 vanilla JS 来实现 OP 所要求的内容,jQuery 方法将是类似的。

function dispatchInputChangeEvent(input)
{
    // Grabbed from the linked answer, there's a few approaches to this.
    input.dispatchEvent(new Event('change', { bubbles: true }));
}

// ...

// inside our execution block, jQuery ready or vanilla DOMContentLoaded for the question's example
document.getElementById('add-rand').addEventListener('click', e => 
{
    const blockNumInputList = document.querySelectorAll('.bulk_number');
    blockNumInputList.forEach(input => 
    {
        input.value = '' + 10; // random number here
        dispatchInputChangeEvent(input);
        /* Note: input text elements store their value as a string: 
         * input.value would need to be converted back to a number. 
         * The type of the input was never stated in the question. */
    });

});

© www.soinside.com 2019 - 2024. All rights reserved.