How to only fire event if flipswitch is manually switched

别说谁变了你拦得住时间么 提交于 2019-12-22 05:15:09

问题


I've created an jQuery Mobile flipswitch like this

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

and I listen to changes on this flipswitch

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

But I don't want the event to be triggered if I change the value of the flipswitch by

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

How do I check if a flipswitch has changed by interacting with it directly or setting a value and refreshing the flipswitch?

I've created an example of the unwanted behavior under this JSFiddle.


回答1:


You need to use .on() to attach change event and .off() to remove it - before you bind it again - whenever you change the value dynamically.

Wrap all your code in pagecreate event, it is equvilant to .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



来源:https://stackoverflow.com/questions/22785646/how-to-only-fire-event-if-flipswitch-is-manually-switched

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!