Onclick函数在返回true时未阻止锚点标记的HREF值

Onclick function is not blocking the HREF value of anchor tag on returning true

本文关键字:HREF 函数 返回 true Onclick      更新时间:2023-09-26

我发现onclick函数必须返回false才能继续href值,返回true才能阻止href值。我在这里也用了同样的。在返回false时,它是正确的,继续URL,但在返回true时,它也打开URL页面。

那么,从onclick函数返回true/false值有什么不同呢。

我使用的是Firefox 9.0.1和IE 7。下面是我的html文件。

<html>
<head>
<script language="JavaScript" type="text/javascript">
function clickthis()
 {
 alert("its onclick Function call ");
 return true;
 }
  </script>
 </head>
 <body >
  <a id="foo" onclick="clickthis();" href="http://google.com">google</a>
 </body>
</html>

我对这种行为感到困惑。

事件处理程序需要返回false以阻止正常的链接操作,并且不能仅调用函数;如果您希望抑制该操作,则处理程序本身需要返回值CCD_。所以属性应该是

onclick="return clickthis();"

您应该对事件对象使用preventDefault方法。示例:http://jsfiddle.net/lolo/vD5hK/

[用Firefox 35.0.1]测试

我为它做了一些解决方案。如果检测到锚,并定义了href,则单击将接管并重定向页面。

代码:

<html><title></title><body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<script language="JavaScript" type="text/javascript">
function clickthis(e, obj)
{
console.log('click');
    e.preventDefault();
        $.ajax({url: "a.html", 
        success: function(result){
            console.log('ajax success');
            makeRedirect(obj);
        },
        error: function(result){        
            console.log('ajax error');
            makeRedirect(obj);
        }       
    });
}
function makeRedirect(obj){
    if (obj && obj.tagName == 'A' && obj.href){
        console.log('redirecting');
        window.location = obj.href;
    }
}
</script>
<a id="foo" onclick="clickthis(event,this);" href="http://www.google.com">###3 google 3###</a>
</body></html>

注意:你甚至可以在所有异步逻辑完成后进行重定向。。。

您需要使用onclick="return clickthis();",单击this()必须返回false。

如果你要进行渐进增强(即,如果用户没有启用javascript,则转到google.com,如果用户启用了javascript,则显示警报),那么你希望你的标记看起来像这样:

<html>
<head>
<script language="JavaScript" type="text/javascript">
function clickthis(e)
 {
    e.preventDefault();
    alert("its onlcick Function call ");
    return false;
 }
  </script>
 </head>
 <body >
  <a id="foo" onclick="clickthis(event);" href="http://google.com">google</a>
 </body>
</html>