繁体   English   中英

如果手动切换flipswitch,如何仅触发事件

[英]How to only fire event if flipswitch is manually switched

我已经创建了这样的jQuery Mobile flipswitch

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

但是如果我改变flipswitch的值,我不希望触发事件

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

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

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

您需要使用.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);
    });
});

演示

暂无
暂无

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

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