【问题标题】:Javascript error only on Safari仅在 Safari 上出现 Javascript 错误
【发布时间】:2015-08-31 23:58:19
【问题描述】:

我有一个可以在除 Safari 之外的所有浏览器中正常运行的 javascript。

代码非常简单,基本上当我更改文本字段的值(数值)时,<b> 的内容也会更改

这里是代码

$(document).on('change', '.priceAmount', function(e) {
 e.preventDefault();
 $((e.target).closest('div.price_info')).find('> .supplierPrice').html(
 ($(this).val() + 10);
});

对应的HTML是

<div class="price_info">        
   <input type="number" class="priceAmount">    
   <b class="supplierPrice">20</b>
</div>

&lt;b&gt;里面的20是我在输入框中输入10时js插入的。

Safari 给我这个错误

TypeError: undefined is not a function (evaluating '(e.target).closest('div.price_info')')

触发事件时,Safari 似乎没有接收到元素

【问题讨论】:

    标签: javascript jquery safari


    【解决方案1】:

    使用 $(this) 代替 e.target。建议使用 parseInt

    $(document).on('change', '.priceAmount', function(e) {
     e.preventDefault();
     $(this).closest('div.price_info').find('.supplierPrice').html(parseInt($(this).val()) + 10);
    });
    

    Fiddle

    【讨论】:

    • closest 之后的额外)
    【解决方案2】:

    您错过了e.target 中的$

    $($(e.target).closest('div.price_info'))
    //^
        .find('> .supplierPrice').html(parseInt($(this).val(), 10) + 10);
    

    或者,您也可以使用$(this)

    $(this).closest('div.price_info')
        .children('.supplierPrice')
        .html(parseInt($(this).val(), 10) + 10);
    

    语法错误在您的代码中:

    ( 之后的额外html 方法:

    $((e.target).closest('div.price_info')).find('> .supplierPrice').html(
     ($(this).val() + 10);
    //^
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-25
      • 2011-04-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多