日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

关于 href=javascript:; 到底做了什么

發布時間:2025/3/21 javascript 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 关于 href=javascript:; 到底做了什么 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

這幾天正在仿寫一個網站demo,有些細節地方想不明白就查看了網站碼源學習學習,發現自己的<a>標簽與源碼諸多不同,雖然之前就看過很多的網站的代碼都有這個<a href="javascript:;"></a>或這個<a href="javascript:void(0);></a>",但還是產生了疑問:

1.這種寫法的作用是什么?

2.為什么這樣寫?

于是隨手Google之,排名第一的是張鑫旭大神的一篇文章,第二個就是在stackoverflow上的問答。

由于張大神的這篇文章也是提出了自己的一些疑問而解釋的較少,故在這里就不細說了。

接下來我就來看看stackoverflow上關于這個問題的高票回答。

An <a>element is invalid HTML unless it has either an href or name attribute.

If you want it to render correctly as a link (ie underlined, hand pointer, etc), then it will only do so if it has a href attribute.

Code like this is therefore sometimes used as a way of making a link, but without having to provide an actual URL in the href attribute. The developer obviously wanted the link itself not to do anything, and this was the easiest way he knew.

He probably has some javascript event code elsewhere which is triggered when the link is clicked, and that will be what he wants to actually happen, but he wants it to look like a normal <a>tag link.

Some developers usehref='#'for the same purpose, but this causes the browser to jump to the top of the page, which may not be wanted. And he couldn't simply leave the href blank, because href=''is a link back to the current page (ie it causes a page refresh).

There are ways around these things. Using an empty bit of Javascript code in the href is one of them, and although it isn't the best solution, it does work.

看完之后真的是豁然開朗,故寫此文以敬之。

現在我就來總結一下這位名叫Spudley的大神(是真的大神,被他的主頁震驚了)的回答要點:

1.首先<a>標簽要想起作用就必須有個name屬性或是href屬性,這是前提;

2.其次<a>標簽若想有類似鏈接的效果,比如下劃線或者是手狀的鼠標等,就需要有href屬性;

3.有的人會使用href="#"來實現相同的目的,但是#會使瀏覽器跳轉到頁面頂部;若使用href=''的話會重新刷新頁面,顯然也是不必要的。

4.在href中使用一個空的Javascript代碼是其中的一個解決方法,雖然它不是最好的解決方案,但它可以工作。

真的是遠離某度保性命,常用google漲姿勢呀。

轉載于:https://www.cnblogs.com/syqcoding-life/p/9821815.html

總結

以上是生活随笔為你收集整理的关于 href=javascript:; 到底做了什么的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。