简体   繁体   English

单击超链接后如何防止重定向?

[英]How to prevent redirect after hyperlink click?

I have following html+ js code:我有以下 html+ js 代码:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>

<a href="#" id=key onclick="func(0)">foo</a>

</body>

<script type="text/javascript">
function func(k){
    alert(1);
    return false;
}   
</script>
</html>

Can you explain how to refactor following code that after click on href code func executes but # doesn't add to the URL and page shouldn't be reload?您能解释一下如何重构以下代码吗?在单击 href 代码后, func会执行,但 # 不会添加到 URL 并且不应重新加载页面?

Use javascript:void(0);使用javascript:void(0); instead of # as follows:而不是#如下:

<a href="javascript:void(0);" id=key onclick="func(0)">foo</a>

您可以简单地删除 href 属性:

<a id='key' onclick="func(0)">foo</a>

Change it to:将其更改为:

                            vvvvvvv
<a href="#" id=key onclick="return func(0)">foo</a>

我想你忘记了“key”中的引号

<a href="#" id="key" onclick="func(0)">foo</a>

To be more semantically correct I would be using a button with the following onclick:为了在语义上更正确,我将使用带有以下 onclick 的按钮:

<button id=key onclick="return func(0)">foo</button>

This way there is no need to hack around with e.preventDefault / return false.这样就不需要修改 e.preventDefault / return false。

Inside func, you could do:在 func 中,您可以执行以下操作:

func(event){ event.preventDefault(); /* More code here! */ }

preventDefault will prevent redirection, after that line, you could add any logic you want. preventDefault将阻止重定向,在该行之后,您可以添加任何您想要的逻辑。

However, if you don't want a redirect, it is recommended to use a button instead of an a但是,如果您不想重定向,建议使用button而不是a

If we want to stop redirect.如果我们想停止重定向。 We have have to return false.So we can do like that: html:我们必须返回 false。所以我们可以这样做:html:

 <a onclick="return check()" href="{% url 'app_name:delete_url' item.id %}" title='Delete Item' class="btn btn-sm btn-outline-success mr-1"
 <i class="fa fa-trash"></i></a>

script:脚本:

function check(){
    if (confirm("Do you want to delete?") == true) {
        return true;
    } else {
        //cancle 

       return false
        
    }
}

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

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