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

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 前端技术 > javascript >内容正文

javascript

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

發(fā)布時(shí)間:2025/3/21 javascript 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 关于 href=javascript:; 到底做了什么 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

這幾天正在仿寫(xiě)一個(gè)網(wǎng)站demo,有些細(xì)節(jié)地方想不明白就查看了網(wǎng)站碼源學(xué)習(xí)學(xué)習(xí),發(fā)現(xiàn)自己的<a>標(biāo)簽與源碼諸多不同,雖然之前就看過(guò)很多的網(wǎng)站的代碼都有這個(gè)<a href="javascript:;"></a>或這個(gè)<a href="javascript:void(0);></a>",但還是產(chǎn)生了疑問(wèn):

1.這種寫(xiě)法的作用是什么?

2.為什么這樣寫(xiě)?

于是隨手Google之,排名第一的是張?chǎng)涡翊笊竦囊黄恼?#xff0c;第二個(gè)就是在stackoverflow上的問(wèn)答。

由于張大神的這篇文章也是提出了自己的一些疑問(wèn)而解釋的較少,故在這里就不細(xì)說(shuō)了。

接下來(lái)我就來(lái)看看stackoverflow上關(guān)于這個(gè)問(wèn)題的高票回答。

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.

看完之后真的是豁然開(kāi)朗,故寫(xiě)此文以敬之。

現(xiàn)在我就來(lái)總結(jié)一下這位名叫Spudley的大神(是真的大神,被他的主頁(yè)震驚了)的回答要點(diǎn):

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

2.其次<a>標(biāo)簽若想有類(lèi)似鏈接的效果,比如下劃線(xiàn)或者是手狀的鼠標(biāo)等,就需要有href屬性;

3.有的人會(huì)使用href="#"來(lái)實(shí)現(xiàn)相同的目的,但是#會(huì)使瀏覽器跳轉(zhuǎn)到頁(yè)面頂部;若使用href=''的話(huà)會(huì)重新刷新頁(yè)面,顯然也是不必要的。

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

真的是遠(yuǎn)離某度保性命,常用google漲姿勢(shì)呀。

轉(zhuǎn)載于:https://www.cnblogs.com/syqcoding-life/p/9821815.html

總結(jié)

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

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。