JavaScript - how to detect a programmatic value change on a select element (dropdown)

前端 未结 2 1465
小鲜肉
小鲜肉 2021-01-22 01:58

In JavaScript, I need to detect when the value of a certain select element has changed for any reason, including programmatically.

The onchange event i

2条回答
  •  借酒劲吻你
    2021-01-22 02:24

    var targetSelect = $('appropriate selector');
    var lastVal = targetSelect.val();
    
    setInterval(function() {
        var newVal = targetSelect.val();
        if(newVal !== lastVal) {
            // it changed, fire an event or process it
        }
        lastVal = newVal;
    }, intervalSpacing);
    

    The lower the value you pass to 'intervalSpacing' the more CPU time you spend, but the sooner you realize it changed. Tune cautiously.

提交回复
热议问题