【问题标题】:Ajax Uncaught TypeError: Cannot read property 'click' of nullAjax 未捕获类型错误:无法读取 null 的属性“单击”
【发布时间】:2016-05-08 02:41:05
【问题描述】:

我无法找出错误的原因。我不断收到Uncaught TypeError: Cannot read property 'click' of null 错误。我确实在按钮中定义了.product-btn 类。

这是完整的代码:

<script type="text/javascript">
    $('.product-btn').click(function(){
        if($(this).attr('data-action')=="add"){
          ajaxSubmit('/add/product/'+$(this).attr('data-id')+'/');
              $(this).attr('data-action','remove');
              $(this).children('span').html('Remove from cart');
      }else{
        ajaxSubmit('/remove/product/'+$(this).attr('data-id')+'/');
            $(this).attr('data-action','add');
            $(this).children('span').html('Request Price');
      }
    });
</script>

还有按钮:

<button class="btn btn-sm btn-inverse btn-embossed product-btn" data-action="add" data-id="<?php echo $productId; ?>"><span><?php echo $this->__('Add to Cart') ?></span></button>

【问题讨论】:

  • 你包含了 jQuery 吗? console.log($.fn.jquery) 的输出是什么?
  • 是的,我已经包含了 jQuery。我得到Uncaught TypeError: Cannot read property 'jQuery' of undefinedconsole.log($.fn.jquery)
  • 那么$.fn 不应该是undefined 再次检查包含
  • jquery 应该包含在你的脚本之前(最好包含在 head 部分中),并且还应该在关闭 body 标记之前包含你的脚本。
  • @Andreas 我仍然收到Uncaught TypeError: Cannot read property 'jquery' of undefined 这可能是因为prototype.js 因为我也包含了它吗? @viktor-kukurba 是的,jQuery 位于标题的首位。

标签: javascript ajax


【解决方案1】:

把里面的函数准备好

$(document).ready(function(){
 $('.product-btn').click(function(){
                if($(this).attr('data-action')=="add"){
                  ajaxSubmit('/add/product/'+$(this).attr('data-id')+'/');
                  $(this).attr('data-action','remove');
                  $(this).children('span').html('Remove from cart');
                }else{
                    ajaxSubmit('/remove/product/'+$(this).attr('data-id')+'/');
                        $(this).attr('data-action','add');
                        $(this).children('span').html('Request Price');
                  }
                });
        });

【讨论】:

  • 如果选择器与 DOM 中的任何节点都不匹配,jQuery 将不会返回 null
  • 否,但它不会因cannot read ... of null 错误而崩溃
猜你喜欢
  • 2016-11-30
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 2021-12-01
  • 2022-07-02
  • 2022-06-14
相关资源
最近更新 更多