Onclick无法正常工作。 无法读取null的属性“click”

将脚本加载到Magento商店时,我不断从浏览器控制台收到以下错误。 所有它正在侦听的是div上的onclick事件但我收到此错误:

“未捕获的TypeError:无法读取属性’click’的null。”

该脚本在JSfiddle中运行,所以我真的不太确定它为什么不起作用。 我已经尝试将它封装在$(document).ready()中,但我收到了同样的错误。

码:

var step = 0; var deviceType = ""; var modelType = ""; function showGen(){ $('.phoneTypes').css("display", "none"); if (deviceType == "Samsung"){ $('.sphoneGens').css("display", "block"); } if (deviceType == "iPhone"){ $('.iphoneGens').css("display", "block"); } if (deviceType == "iPad"){ $('.ipadGens').css("display", "block"); } } // Pick Device Type $('.choicelabel').click(function(){ deviceType = $(this).children('input').val(); showGen(); }); //Pick Device Gen $('.choiceType').click(function(){ modelType = $(this).children('input').val(); //$(".iphoneGens").css("display", "none"); console.log(deviceType); console.log(modelType); $(this).parents(".row").hide(); }); 

任何帮助调试此问题将不胜感激。

TL; DR:

 jQuery( document ).ready(function( $ ) { // Code using $ as usual goes here. // And document is ready too }); 

有什么问题?

Prototype.js是在jQuery之后加载的,并且覆盖了全局$符号。

我们该如何处理它?

您仍然可以使用jQuery全局。 只需在任何地方使用它,你想要使用$

 // Pick Device Type jQuery('.choicelabel').click(function(){ deviceType = jQuery(this).children('input').val(); showGen(); }); //Pick Device Gen jQuery('.choiceType').click(function(){ modelType = jQuery(this).children('input').val(); //jQuery(".iphoneGens").css("display", "none"); console.log(deviceType); console.log(modelType); jQuery(this).parents(".row").hide(); }); 

您还可以定义一些简化以简化它:

 jQ = jQuery; 

这种情况的常见最佳做法是使用IIFE包装代码:

 ;(function($){ // see note-1 // Use $ here! It's jQuery now $(function(){ // be sure DOM was loaded before work with it(ex: binding events) }); })(jQuery); 

这不会增加全球范围并实现我们的需求。
你总是可以注入一些其他库(prototypejs?)和别名你希望这个IIFE。

note-1:IIFE之前的分号保护javascript不受以前表达式的影响,错过分号将被解释为函数调用。


jQuery本身为这种情况提供了简写:

 jQuery( document ).ready(function( $ ) { // Code using $ as usual goes here. // And document is ready too }); 

该网站没有使用jQuery,它使用的是prototypejs