简体   繁体   English

如果已通过“选择”框的更改事件“选择”或“取消选择”一个选项,则查找

[英]FInd if an option has been 'selected' OR 'de-selected' via change event of Select box

I have a html multi-select select box. 我有一个HTML多选选择框。 When i select/de-select values in a change event is fired on it. 当我选择/取消选择更改事件中的值时,会触发它。

Whats the best way to know from the event that the event is because of an element being selected or deselected? 从事件中知道事件是由于元素被选中或取消选中的最佳方式是什么? I don't want its value, just whether the change event is because of 'selection' or 'de-selection'. 我不希望它的值,只是更改事件是因为“选择”还是“取消选择”。

Making a few assumptions here, you have a multi-select and you just need to know if there has been a selection or not. 在这里做一些假设,您有一个多重选择,您只需要知道是否有一个选择。

Then, you just need to check the length of selected options with a cached value. 然后,您只需要使用缓存的值检查所选选项的长度即可。

See this fiddle: http://jsfiddle.net/2uudx/1/ 看到这个小提琴: http : //jsfiddle.net/2uudx/1/

Not the most elegant or optimized way, but a direction. 不是最优雅或最优化的方法,而是一个方向。

var sel = 0;
$('#mySelect').on("change", function() {
    var newsel = $(this).find(":selected").length;
    if (newsel > sel) {
        // selected
    } else {
        if (newsel < sel) {
            // de-selected
        } else {
            // no-change
        }
    }
    sel = newsel;
});

If you really need to compare the values which were selected or de-selected, then instead of caching the length, you cache the selected values in an array. 如果您确实需要比较选定或取消选定的值,则可以将选定的值缓存在数组中,而不是缓存长度。 On change , compare the currently selected values to the cached array. 更改时 ,将当前选择的值与缓存的数组进行比较。

Hope that gives a suitable pointer. 希望能给出合适的指针。

Update : 更新

Using values to compare more accurately, as mentioned above by way of arrays. 使用值更精确地进行比较,如上面通过数组所述。

Here is a sample fiddle: http://jsfiddle.net/u9XE4/3/ 这是一个样本小提琴: http : //jsfiddle.net/u9XE4/3/

var sel = [];
$('#s1').on("change", function() {
    var newsel = $(this).val();
    var same = compareArray(newsel, sel);
    if (same) {
        // no-change
    } else {
        if ((!same) && ((newsel.length == sel.length) || (newsel.length < sel.length))) {
            // de-selected
        } else {
            // selected
        }
    }
    sel = newsel;
});

function compareArray(a, b) {
    $.each( a, function( key, value ) {
        var index = $.inArray( value, b );
        if( index != -1 ) {
            return true;
        }
    });
    return false;
}

hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM