[英]jQuery - stopping anchor <a> from redirecting using onClick=“function(this)”
[英]How to stop an anchor from redirecting using JQuery
如果用戶未登錄,如何停止錨標記重定向到另一個頁面? 我有一個功能來檢查用戶是否登錄。 我想用 JQuery 或 JavaScript 來完成。 到目前為止,這是我嘗試過但沒有結果的方法:
<a href="www.somewhere.com" id="yes">Read More</a>
<script type="text/javascript">
$(document).ready(function(){
$('a').click(function(){
var id = $(this).attr('id');
if(id == 'yes'){
//i want to prevent
}else{
//redirect
}
});
});
</script>
請使用http://api.jquery.com/event.preventDefault/
演示http://jsfiddle.net/aRBY4/6/
e.preventDefault()
引用
如果調用該方法,則不會觸發事件的默認動作。
另外,如果我建議閱讀: .prop() vs.attr()
希望這可以幫助,
示例代碼
$('a').click(function(event){
event.preventDefault();
//do whatever
});
在你的情況下,請試試這個
$(document).ready(function() {
$('a').click(function(event) {
var id = $(this).attr('id');
if (id == 'yes') {
event.preventDefault();
//i want to prevent
} else {
//redirect
}
});
});
將您的點擊事件處理程序更改為此
$('a').click(function(e){
var id = $(this).attr('id');
if (id == 'yes')
{
e.preventDefault();
e.stopPropagation();
}
else
{
//redirect
}
});
試試這個
$("a").on("click",function(e){
e.preventDefault();
alert("Clicked");
});
快樂編碼;
使用event.preventDefault() 。 它用於防止事件的默認動作。
<script type="text/javascript">
$(document).ready(function(){
$('a').click(function(){
var id = $(this).attr('id');
if(id == 'yes'){
event.preventDefault()
}else{
//redirect
}
});
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.