JavaScript - 如何检测select元素上的程序化值更改(下拉列表) [英] JavaScript - how to detect a programmatic value change on a select element (dropdown)

查看:68
本文介绍了JavaScript - 如何检测select元素上的程序化值更改(下拉列表)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,我需要检测某个select元素的值何时更改任何原因,包括以编程方式。

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

仅当用户手动更改所选值时才会触发onchange事件,而当其他JavaScript以编程方式更改值时,

The onchange event is only fired when the user changes the selected value manually, not when other JavaScript changes the value programmatically.

这是一个包含各种插件组件的网站,我们不想破解(在某些情况下不能破解up,因为代码驻留在其他网站上)。 因此,只要有程序化更改,我自己就会触发更改事件。我需要实际监控select, listen ,以便更改值。

This is a website with a variety of plugin components that we don't want to hack up (and in some cases can't hack up, since the code resides on other sites). So triggering the change event myself whenever there is a programmatic change isn't an option. I need to actually monitor the select, listen to it, for a change in value.

这可能吗?我还没找到办法。

Is this possible? I haven't found a way.

是否有一些我可以用来经常轮询价值寻找变化的库?或者其他方式?

Is there perhaps some library I can use to frequently poll the value looking for change? Or some other way?

推荐答案

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);

您传递给'intervalSpacing'的值越低,您花费的CPU时间就越多,但您越快意识到它改变了。小心调整。

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

这篇关于JavaScript - 如何检测select元素上的程序化值更改(下拉列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆