天天看點

a标簽中onclick 和 href同時存在,隻執行onclick而不執行href跳轉

之前處理導航欄和tab關聯的時候看别人對插件的使用,在a标簽中觸發事件,擷取a标簽的href,data-id屬性,來建立一個新的tab,并且不處罰href,在iframe中根據href打開新的iframe。

用法:

<div>
    <a class="b" href="111.html" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow"  id="a" onclick="qwe();event.returnValue=false;">123</a>
    <a class="b" href="111.html" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow"  id="a" onclick="qwe();return false;">123</a>
</div>


<script>
    function qwe(){
        alert("a");
    }
</script>
           

兩種寫法都可以。

使用JQ,不啟用onclick:

<div>
    <a class="b" href="111.html" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow"  id="a" >123</a>
</div>

<script type="text/javascript">

$(document).ready(function(){
 
    $(".b").click(function(){
        alert("1");
        return false;
    });
})
       

</script>
           

隻需要給click事件傳回一個false就不會執行href連結跳轉。

上面的寫法是動态建立tab,需要擷取href的值,

另外如果不需要href的值可以直接這樣寫,實作href失效:

<div>
    <a href="javascript:void(0)" target="_blank" rel="external nofollow"  onclick="qwe()">123</a> 
</div>
           

javascript:void(0),計算的值是0,此時是個死連結。