问题描述
使用 JQuery 或 JavaScript,我想检测用户何时选择了一个值,即使他们没有更改已选择的值.
Using JQuery or JavaScript, I want to detect when a user selects a value, even if they don't change the already selected value.
如何实现?
我试过了 -
$('#MyID').select(function(){ /*my function*/ });
和
$('#MyID').change(function(){ /*my function*/ }); //nothing changing, so this fails
但它们不起作用.
示例 - 我有一个包含年份列表的下拉列表,没有选择任何内容,用户选择1976",我运行一个函数.选择1976"后,用户再次单击下拉菜单并选择1976"再次,我想再次运行该功能.
Example - I have a dropdown with a list of years in it with nothing selected, the user selects "1976", I run a function. With "1976" selected, the user clicks on the dropdown again and selects "1976" again, I want to run the function again.
推荐答案
所有系统运行(至少在第二次点击时...)
all systems go (on second click at least...)
将开关设置为在选择时运行,并在捕获和/或在 blur
上重置开关.
Set a switch to run on selection, and reset the switch after it's captured and/or on blur
.
var go = false;//switch off
$('#MyID').on('click',function() {//on click
if (go) {//if go
//do stuff here with $(this).val()
go = false;//switch off
} else { go = true; }//if !go, switch on
}).on('blur', function() { go = false; });//switch off on blur
做了一个小提琴:http://jsfiddle.net/filever10/2XBVf/
对于键盘支持也是如此,这样的事情应该可以工作.
edit: for keyboard support as well, something like this should work.
var go = false;//switch off
$('#MyID').on('focus active click',function() {//on focus/active
doit($(this));//do it
}).on('change', function() {
go=true;//go
doit($(this));//and doit
}).on('blur', function() { go = false; });//switch off on blur
function doit(el) {
if (go) {//if go
//do stuff here with el.val()
go = false;//switch off
} else {go=true}//else go
}
做了一个小提琴:http://jsfiddle.net/filever10/TyGPU/
这篇关于即使未更改,也会选择 JQuery 检测下拉值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!