【问题标题】:How to only fire event if flipswitch is manually switched如果手动切换翻转开关,如何仅触发事件
【发布时间】:2014-04-01 12:16:18
【问题描述】:

我已经创建了一个像这样的 jQuery Mobile 翻转开关

<select id="flip" data-role="flipswitch">
    <option value="animal">Lion</option>
    <option value="flower">Rose</option>
</select>

我会听到这个翻转开关的变化

$( document ).on( 'change', '#flip', function( e ) {
   console.log( 'changed' );
}

但是如果我改变翻转开关的值,我不希望事件被触发

$( '#flip' ).val( 'flower' ).flipswitch( 'refresh' );

如何通过直接与其交互或设置值并刷新翻转开关来检查翻转开关是否已更改?

我在this JSFiddle 下创建了一个不需要的行为示例。

【问题讨论】:

标签: javascript jquery jquery-mobile event-handling jquery-mobile-flipswitch


【解决方案1】:

您需要使用.on() 附加change 事件并使用.off() 删除它 - 在再次绑定之前 - 每当您动态更改值时。

将所有代码包装在pagecreate 事件中,相当于.ready()

$(document).on("pagecreate", "#main", function () {

    /* change event handler */
    function flipChanged(e) {
        var id = this.id,
            value = this.value;
        console.log(id + " has been changed! " + value);
    }

    /* add listener - this will be removed once other buttons are clicked */
    $("#flip").on("change", flipChanged);

    $('#setlion').on('vclick', function (e) {
        $("#flip")
            .off("change") /* remove previous listener */
            .val('animal') /* update value */
            .flipswitch('refresh') /* re-enhance switch */
            .on("change", flipChanged); /* add listener again */
    });

    $('#setrose').on('vclick', function (e) {
        $("#flip")
            .off("change")
            .val('flower')
            .flipswitch('refresh')
            .on("change", flipChanged);
    });
});

Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    • 2021-09-16
    • 2017-12-10
    • 2020-06-21
    相关资源
    最近更新 更多