【问题标题】:jQuery click handler code not working on mobilejQuery单击处理程序代码在移动设备上不起作用
【发布时间】:2016-02-22 00:52:02
【问题描述】:

我一直在努力解决这个问题,并在这里(和其他地方)找到了多个“解决方案”,但似乎没有什么对我有用。我忽略了什么吗?

在桌面上一切正常,但在移动设备(特别是 iOS Safari)上,点击事件代码不起作用。

** 澄清一下……点击事件正在触发……如果我发出警报,它就会触发。但是 DOM 没有被操纵。同样,这仅适用于移动设备。 DOM 操作代码 100% 在桌面上运行。

这是一个 WordPress 网站,这就是我必须解决无冲突模式的原因。下面是我的代码...

HTML

<button id="add-ingredient" class="add-button" style="cursor: pointer;">Add</button>

jQuery

jQuery(document).ready(function($){

        $('#add-ingredient').on('click', function(event) {
            event.preventDefault();
            var lastIngredient = $(this).prev('[class^="ingredient-').attr('class');

            var x = lastIngredient.replace('ingredient-', '');
            x = parseInt(x) + 1;
            var html = '<div class="ingredient-'+ x + '">' +
                    '<input type="text" name="recipe_ingredients['+ x + '][amount]" id="amount" placeholder="amount" value="<?php echo $recipe_ingredients['+ x + '][amount]; ?>" />' +
                    '<input type="text" name="recipe_ingredients['+ x + '][unit]" id="unit" placeholder="unit" value="<?php echo $recipe_ingredients['+ x + '][unit]; ?>" />' +
                    '<input type="text" name="recipe_ingredients['+ x + '][ingredient]" id="ingredient" placeholder="ingredient" value="<?php echo $recipe_ingredients['+ x + '][ingredient]; ?>" />' +
                    '<input type="text" name="recipe_ingredients['+ x + '][notes]" id="notes" placeholder="notes" value="<?php echo $recipe_ingredients['+ x + '][notes]; ?>" />' +
                '</div>';
            $(this).before(html);
            return false;
        });
    });

【问题讨论】:

  • 当您说“点击事件不起作用”时,您的意思是它永远不会触发回调吗?如果您在event.preventDefault() 之前添加alert(event)console.log(event),您会看到回复吗?
  • 对不起,我应该更清楚。回调被触发,但 DOM 未被操作。

标签: javascript jquery wordpress mobile


【解决方案1】:

如果你删除event.preventDefault();,回调应该会被执行。

如果您想阻止默认行为,我建议您监听 touchstart 事件:

$('#add-ingredient').on('click touchstart', function(event) {
  console.log(event);
});

【讨论】:

  • 尝试了该设置,但没有成功。它只是触发没有 event.preventDefault 的表单提交。就像我说的,移动 Safari 会触发回调,但不会发生 DOM 操作。如果我在回调代码的顶部添加一个警报,则会触发......但就是这样。
【解决方案2】:

我发现我的 jQuery 代码中有一个错误,我使用了错误的选择器。事实证明 Chrome 允许它通过其他浏览器(iOS Safari)不能通过的地方。我在这里发现了错误...

var lastIngredient = $(this).prev('[class^="ingredient').attr('class');

问题出在 class^="ingredient..... 选择器中。注意我没有关闭 [ ]。代码应该如下......

var lastIngredient = $(this).prev('[class^="ingredient"]').attr('class');

这样做可以让移动设备上的一切正常运行。

【讨论】:

    猜你喜欢
    • 2019-06-26
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 2018-07-11
    • 2015-04-22
    相关资源
    最近更新 更多