2015-08-16 21 views
-1

我得到這個遺漏的類型錯誤「上」讀取屬性:遺漏的類型錯誤:不能爲空

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

這真是難住我了,如果有人能幫助我解決這個問題,將不勝感激。

謝謝,尼克

+0

,並請把你的HTML元素與此類要麼 –

+0

還請確保您的jQuery的版本是等於或大於'1.7' –

+0

您應該顯示HTML聲明以及 –

回答

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); 
0

問題是與$。您的$與jQuery和prototypejs發生衝突。

每當你寫jQuery代碼,嘗試使用自調用函數與jQuery作爲參數。例如:

(function($){//You can use any character instead $ here. 
//Your code here to use $. 
})(jQuery); 

或另一種方式是使用jQuery字代替$。例如:

jQuery('.addtocart').on('click', function(){ 
    //Your code here. 
}); 

在你的代碼,$由原型中使用,因爲當腳本執行有帶班.addtocart沒有元素$('.addtocart')被返回null。這就是爲什麼它在訪問null *($('。addtocart'))*時拋出錯誤。

如果你想添加jQuery的唯一事件處理程序。然後用jQuery word代替$。

//when add to cart link is clicked... 
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')); 
    } 

});