Onclick JS 函数调用,仅在 Safari 控制台中返回“找不到变量”

Jas*_*ehl 5 javascript safari

所以我写了一个非常简单的 JS 函数,其工作原理如下。

有一个按钮,其代码如下:

<button type="submit" class="large button" onclick="addCart(76,95,73,96);">
    <i class="icon-shopping-cart"></i> Add to Cart
</button>
Run Code Online (Sandbox Code Playgroud)

现在,当单击该按钮时,下面的页面中将添加一个非常简单的功能,如下所示:

<script type="text/javascript">
    function addCart(pid, pattr, pval, pscent = 0) {
    ...
    }
</script>
Run Code Online (Sandbox Code Playgroud)

这在 Chrome、Firefox、Chrome for Mobile、Safari for Mobile 中完美运行。

但这似乎不适用于Mac 上的 Safari。相反,我收到以下错误:

ReferenceError:找不到变量:addCart

我不明白为什么。对我来说添加监听器很困难,因为有 7 个按钮和大量正在发送的变量,而且我宁愿像我当前正在做的那样发送它们。

Jas*_*ehl 3

我终于找到问题了。

该函数在 Safari 中产生错误,因此从未被定义。我将函数更改为以下内容:

function addCart(pid, pattr, pval, pscent) {
    pscent = (typeof pscent !== 'undefined') ?  pscent : 0;
...
}
Run Code Online (Sandbox Code Playgroud)

请注意,最大的区别是我不再使用函数来声明“pscent”的默认值,而是使用老式方法。不确定这是否是由旧版本的 Safari 引起的还是其他原因。

如果您因为类似的错误而来到这里,请在函数中查找一些潜在的 JS 错误,这些错误将阻止函数被声明。