Onclick无法正常工作.无法读取null的属性'click'

Que*_*ery 1 javascript jquery onclicklistener

将脚本加载到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();
});
Run Code Online (Sandbox Code Playgroud)

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

vp_*_*rth 5

TL; DR:

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

有什么问题?

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();
});
Run Code Online (Sandbox Code Playgroud)

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

jQ = jQuery;
Run Code Online (Sandbox Code Playgroud)

这种情况的常见最佳做法是使用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);
Run Code Online (Sandbox Code Playgroud)

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

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


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

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