2014-02-24 41 views
0

內躲藏,我試圖找出一種方法來隱藏和我的網頁上重新出現的事情:的Javascript在線href屬性

<a href="javascript: document.getElementById('something').style.display = 'inline'"> 
prompt 
</a> 
<div id="something" style="display:none"> 
text 
</div> 

爲什麼不是這方面的工作?這是一種讓我在單擊提示時重新顯示文本的方法。

我特別感興趣的是爲什麼不是我的href = javascript部分工作,而不是使用onclick的解決方法。

+4

將內聯JavaScript放在'a'標籤的'onclick'屬性中。 – mafafu

+0

@mafafu謝謝,這個工作,但我仍然對原來的工作不感興趣,因爲我沒有看到故障代碼中的錯誤。 – Kravaros

+0

可能重複[javascript hide/show element](http://stackoverflow.com/questions/6242976/javascript-hide-show-element) – Allende

回答

3

這(apperantly)將做魔術:

<a href="javascript:(function(){document.getElementById('something').style.display = 'inline';})()"> 

但我不會賭它,而且我不能弄清楚爲什麼使用自動執行功能ANOM它的工作原理。

更多關於自執行ANOM功能在這裏:

http://markdalgleish.com/2011/03/self-executing-anonymous-functions/

更關心這個(古?)技術也被稱爲較真爲「立即調用的函數表達式(IIFE)」:

http://benalman.com/news/2010/11/immediately-invoked-function-expression/

我仍然在試圖理解爲什麼它的工作,我認爲這是與此相關的功能是執行d 「inmediatly」,這意味着甚至在傳播點擊事件或瀏覽器嘗試導航之前,可能是瀏覽器/ jsengine訪問href attr之前。

你應該嘗試再使用 「的onclick」 事件:

<a href="#" onclick="document.getElementById('something').style.display = 'inline'"> 
prompt 
</a> 

看到這個問題(與上述有關的技術):

javascript hide/show element

,並使用了JS href屬性相關腳本看到這個問題:

JavaScript function in href vs. onclick