javascript 如何单击将执行但不重定向的链接。
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29079539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to click a link that will execute but not redirect.
提问by chronotrigga
I have a few products in a mySQL database whose links are being retrieved in my script with $producturl. These url's actually add the product to the cart (http://www.example.com/cart/?add-to-cart=1127). I am trying to create a script that will allow the user to add products to the cart but NOT redirect them, just execute the link so the user stays on the same page.
我在 mySQL 数据库中有一些产品,它们的链接正在我的脚本中用 $producturl 检索。这些 url 实际上将产品添加到购物车 ( http://www.example.com/cart/?add-to-cart=1127)。我正在尝试创建一个脚本,允许用户将产品添加到购物车但不重定向它们,只需执行链接以便用户停留在同一页面上。
I am using preventDefault and stopPropgation but it is not working. The alert shows up but the link itself is not executing when I view my cart later the product is not there. Any help?
我正在使用 preventDefault 和 stopPropgation 但它不起作用。警报显示,但当我稍后查看我的购物车时,链接本身并未执行,但产品不在那里。有什么帮助吗?
<?php $producturl = ProductURL::find(array('Product'=>$tube1->Tube1));
if($producturl[0]->URL!=NULL){
echo '<span id="shop">Add Cart NoRedirect</span>';
}
?>
<script type="text/javascript">
$(document).on('click', '#shop', function (event) {
$.post( '<?php echo $producturl[0]->URL; ?>' );
event.preventDefault();
event.stopPropagation();
alert('Product has been added to cart');
});
</script>
回答by michaelward82
Your HTML anchor link:
您的 HTML 锚链接:
<a id='link1' href="http://www.google.com">Link</a>
The jQuery JS required (don't forget to put this inside a DOM ready function):
所需的 jQuery JS(不要忘记将其放在 DOM 就绪函数中):
// Act on clicks to a elements
$("#link1").on('click', function(e) {
// prevent the default action, in this case the following of a link
e.preventDefault();
// capture the href attribute of the a element
var url = $(this).attr('href');
// perform a get request using ajax to the captured href value
$.get(url, function() {
// success
});
});
This demonstrates all the principles required to implement your function.
这演示了实现您的功能所需的所有原则。
The page in question and the URL POSTed to must be on the same subdomain, or cross origin resource sharing must be appropriately enabled on the server otherwise the request will fail due to cross domain restrictions.
有问题的页面和 POST 的 URL 必须在同一个子域,或者必须在服务器上适当地启用跨源资源共享,否则请求将因跨域限制而失败。
回答by Jhonatan Gon?alves
Try:
尝试:
'<a href="#" id="shop">Add Cart NoRedirect</a>'
or
或者
'<a href="javascript: return false;" id="shop">Add Cart NoRedirect</a>'
回答by Pavel Gatnar
You can use an image, a button, a div or a text decorated as link instead of a link.
您可以使用图像、按钮、div 或装饰为链接的文本而不是链接。