未捕获的TypeError:无法读取null的属性'on'

时间:2015-08-16 09:27:48

标签: javascript jquery

我收到了这个Uncaught TypeError:

enter image description here

我不确定是什么导致它,maybes与JQuery有关?

以下是确切的代码:

//when add to cart link is clicked...
$('.addtocart').on('click', function(){

  //get the value of the "data-value" attribute for that link
  var vehicleRegistration = $(this).data('value');
  //save it to localStorage
  localStorage.setItem('vehicleRegistration', vehicleRegistration);


  //read from localStorage
  if( localStorage.getItem('vehicleRegistration') ){
    //add the value to the form input
    $('#field34').val( localStorage.getItem('vehicleRegistration') );
  }

});

以下是它发生的页面:http://drivencarsales.co.uk/book-testdrive

真的让我难过,如果有人能帮我解决这个问题,我将不胜感激。

谢谢,尼克

1 个答案:

答案 0 :(得分:1)

在您的网站中,您添加了prototype.jsjQuery。此处$会调用prototype.js而不是jQuery。因此,请将其更改为:

,而不是代码
jQuery('.addtocart').on('click', function(){

  //get the value of the "data-value" attribute for that link
  var vehicleRegistration = jQuery(this).data('value');
  //save it to localStorage
  localStorage.setItem('vehicleRegistration', vehicleRegistration);


  //read from localStorage
  if( localStorage.getItem('vehicleRegistration') ){
    //add the value to the form input
    jQuery('#field34').val( localStorage.getItem('vehicleRegistration') );
  }

});

或者您也可以这样做:

(function ($) {
    $('.addtocart').on('click', function(){

      //get the value of the "data-value" attribute for that link
      var vehicleRegistration = $(this).data('value');
      //save it to localStorage
      localStorage.setItem('vehicleRegistration', vehicleRegistration);


      //read from localStorage
      if( localStorage.getItem('vehicleRegistration') ){
        //add the value to the form input
        $('#field34').val( localStorage.getItem('vehicleRegistration') );
      }

    });
})(jQuery);