繁体   English   中英

jQuery WebStorage不存储变量单击

[英]jQuery WebStorage not storing variable on-click

我正在尝试存储<a>标记的数据属性,并使用localstorage进行存储,我目前有以下代码块:

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') );
  }

});

我也正在运行prototype.js仅供参考。

然后,我的页面上就有了这个<a>标记,该标记链接到包含表单的另一个页面:

<a href="/book-testdrive" class="addtocart" data-value="NH06LKO" title="Book Test Drive">
    <i class="glyphicon glyphicon-road"></i>
    <span>&nbsp;Book Test Drive</span>
</a>

当我按下<a>标记时,它应该将数据值存储在其中,但是每当我console.log vehicleRegistration变量时,它都会给我带来Uncaught ReferenceError: vehicleRegistration is not defined并且不存储data-value属性。

知道我可能会出错吗? 您可以在下面更好地查看实时站点: http ://drivencarsales.co.uk/used-cars.html

<a>标签在所有列出的车辆上。

谢谢,尼克

由于.addtocart是链接,因此您必须首先停止其默认行为。 将事件传递给单击事件并阻止。 它为我工作。

    <script>
        jQuery('.addtocart').on('click', function(e){
e.preventDefault();
  //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') );
}

});
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM