我已经创建了像这样的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' );
如何通过直接与其交互或设置值并刷新翻转开关来检查翻转开关是否已更改?
我在this JSFiddle下创建了一个不受欢迎行为的示例。
答案 0 :(得分:6)
您需要使用.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 强>