简体   繁体   English

对锚随机运行的preventdefault()函数

[英]Preventdefault() function on an anchor working randomly

I have a e-commerce site I'm working on with sessions, I need to prevent default on a href att on a "a" tag when one of the 2 sessions is empty. 我有一个正在处理会话的电子商务站点,当两个会话之一为空时,我需要防止默认的a标记上的href缺省。 I managed to do it but it will only fail the first time I add ONLY 1 element to the session in question. 我设法做到了,但只会在我仅将1个元素添加到有问题的会话中时才会失败。 To clarify, if I add ONLY 1 element to my "cart" it will still preventdefault, but if I add 2 or more, or remove them in any way or numbers it will work properly preventing only if the cart is empty. 要澄清的是,如果我在“购物车”中仅添加1个元素,它仍然会阻止默认设置,但是如果我添加2个或更多元素,或者以任何方式或数字删除它们,则只有当购物车为空时,它才能正常工作。

As my site refresh the page to submit the data to my cart session I created a variable called data that will be "1" if the session isn't empty and "2" if session is empty, then I echo the variable on a hidden input with id data and use jquery to check the value of the element data and prevent default when it is different than 2. 当我的网站刷新页面以将数据提交到购物车会话时,我创建了一个名为data的变量,如果会话不为空,则为“ 1”,如果会话为空,则为“ 2”,然后在隐藏的变量上回显该变量输入具有id数据的数据,并使用jquery来检查元素数据的值,并在与2不同时防止默认值。

// here I define the variable data // //这里定义变量数据//

<?php 
if(!isset($_SESSION_["shopping_cart"])){
$data = "1";
}else{
$data = "2";
}
?>

//this is my anchor// //这是我的主播//

  <li><a id="checkout" href="/bubale/checkout.php" 
  onclick="check();">CHECKOUT</a></li>

// here I insert $data into a hidden input // //在这里,我将$ data插入隐藏的输入中//

   <input type="hidden" id="data" value="<?php echo $data; ?>">

// here if my script // //如果我的脚本//

   <script type="text/javascript">


$( "#checkout" ).click(function( event ) {
    if ($('#data').val() != "2") {
   event.preventDefault();
   alert("Seu carrinho de compras esta vacio");
}

    });




</script>

It should work just fine BUT for some reason the first element added to the cart will still prevent default, my guess is that $data is not changing for some reason. 但是由于某种原因,它应该可以正常工作,但是添加到购物车中的第一个元素仍然可以防止默认设置,我猜是$ data出于某种原因没有改变。

Any help will be appriciated, even if you have a different way to do this I will be glad to get feedback on this... 任何帮助都将得到帮助,即使您有其他方式可以做到这一点,我也很高兴收到有关此问题的反馈...

May be the function is executed before the document is ready. 该功能可能是在文档准备好之前执行的。 Try to use document.ready function like this: 尝试使用document.ready函数,如下所示:

$( document ).ready(function() {
    $( "#checkout" ).click(function( event ) {
    if ($('#data').val() != "2") {
   event.preventDefault();
   alert("Seu carrinho de compras esta vacio");
}

    });
});

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

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