jquery focus() 在移动设备上不工作(android),phonegap-cordova

jquery focus() not working in mobile(android), phonegap-cordova

我是 jquery 的新手,请帮忙!它在网络上运行良好,但在移动设备上运行不正常。

$(document).on('click', 'label', function(){

    if (!$(this).next('input').is(':checked')) {

        $('input[data-cat-qty="' + $(this).next('input').attr('data-cat') + '"]').textinput("enable");
        $('input[data-cat-qty="' + $(this).next('input').attr('data-cat') + '"]').slider("enable");
        $('input[data-cat-qty="' + $(this).next('input').attr('data-cat') + '"]').focus();

    } else {

        $('input[data-cat-qty="' + $(this).next('input').attr('data-cat') + '"]').textinput("disable");
        $('input[data-cat-qty="' + $(this).next('input').attr('data-cat') + '"]').slider("disable");

    }

});

我很确定 iOS 和 Android 不允许您在输入上触发 focus,除非用户实际访问它。

我在 GitHub 上发现了这个 hack,但它只针对 Android,我不知道它是否也适用于 iOS:

// From Lindsey Simon
/**
 * This is a hack to make text input focus work in Android/PhoneGap
 * where calling el.focus() doesn't actually have the blinking cursor
 * effect = scumbag.
 * @param {Zepto} $el A zepto element.
 */
ws.focus = function($el) {
  var el = $el.get(0);
  el.focus();
  el.setSelectionRange && el.setSelectionRange(0, 0);
};

我找到了解决方案,我使用 "touchstart" 而不是 "click" 它起作用了。

$(document).on('touchstart', 'label', function(){

if (!$(this).next('input').is(':checked')) {

    $('input[data-cat-qty="' + $(this).next('input').attr('data-cat') + '"]').textinput("enable");
    $('input[data-cat-qty="' + $(this).next('input').attr('data-cat') + '"]').slider("enable");
    $('input[data-cat-qty="' + $(this).next('input').attr('data-cat') + '"]').focus();

} else {

    $('input[data-cat-qty="' + $(this).next('input').attr('data-cat') + '"]').textinput("disable");
    $('input[data-cat-qty="' + $(this).next('input').attr('data-cat') + '"]').slider("disable");

}

});