javascript - jQuery,也会在已选择的选项上触发更改

标签 javascript jquery

<分区>

我的 select 有问题。 我希望 already selected 选项也触发 .change() 函数。 目前它仅在选择另一个选项时触发。 如果没有太多的 Soucrecode,我怎么能把这种可能性。也许已经有我不知道的可能性了。

Here a fiddle with an example

编辑:

我或许应该提一下,它应该适用于移动浏览器!

最佳答案

编辑: IE 不能很好地处理它! :(

要支持 IE,您可以使用:

--DEMO--

$(document).ready(function () {
    var con = $('#console');
    $('select').change(function () {        
        /* change also on already selected option */
        con.append('- ' + $(this).val() + '<br/>');
        //$(this).blur();
    }).change().bind('mousedown', function () {
        this.selectedIndex = -1;
        this.selectedIndex = $(this).find('option:selected').index();
    });
});

看看这是否符合您的需求:

--DEMO--

$(document).ready(function () {
    var con = $('#console');
    $('select').change(function () {        
        /* change also on already selected option */
        con.append('- ' + $(this).val() + '<br/>');
    }).change().bind('mousedown', function () {
        //on mousedown, clone SELECT element to display current selected value
        // this would be empty value otherwise when setting current selected index
        // NOTE: seems to be still not as good on IE...
        // FF would need to redefine some margin/padding
        if (!$(this).data('cloned')) $(this).data('cloned', $(this).clone().css({
            position: 'absolute',
            pointerEvents: 'none',
            top: this.offsetTop,
            left: this.offsetLeft,
            margin: 0
        }).appendTo('body'));
        // here set selectedIndex of SELECT element to not defined index
        // this would let on change event to be fired in all cases
        this.selectedIndex = -1;
    }).blur(function(){
        // on blur, remove cloned SELECT element and reset specific data object
        if ($(this).data('cloned')) {
            this.value = $(this).data('cloned').val();
            $(this).data('cloned').remove();
            $(this).data('cloned', null);
        }
    });
});

关于javascript - jQuery,也会在已选择的选项上触发更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23732970/

相关文章:

javascript - 如何使用 child-parentnode 将此 javascript 编码为 jquery?

javascript - 悬停时具有边框半径和不透明度的图像

javascript - 将 pdo 查询的结果保存到 javascript 变量

javascript - 使用 CDN 库和外部样式表将 HTML 转换为 PDF

javascript - jquery/js/html 叠加按钮

javascript - Dojo DataGrid、jQuery Grid 还是 DataTables 哪个更好?

javascript - 何时在 javascript/jQuery 中使用 "$"

javascript - 下拉菜单和 codeigniter 的问题

javascript - 在 React 中使用渐变 API 自定义下划线

javascript - 在 Alfresco 中,有没有办法从 java 脚本取消部署定义?