2012-11-17 25 views

回答

2

爲了使它不顯眼的工作在早期IE等主流瀏覽器:

的HTML:

<button id="the-important-button">Submit</button>​ 

的JavaScript:

var theButton = document.getElementById('the-important-button'); 

function hideTheButton() { 
    this.style.display = 'none'; 
} 

function addEvent(target, type, handler) { 
    if (target.addEventListener) { 
     target.addEventListener(type, handler, false); 
    } else if (target.attachEvent) { 
     target.attachEvent('on' + type, function() { 
      return handler.call(target, window.event); 
     }); 
    } else { 
     target['on' + type] = handler; 
    } 
} 

addEvent(theButton, 'click', hideTheButton); 

請注意addEvent是一個通用的函數,可以在早期的IE和其他現代瀏覽器上正常工作。您可以添加與上面最後一行代碼類似的其他事件。

http://jsfiddle.net/W37Fb/5/

+0

當心'.attachEvent'。它會在'hideTheButton'函數中將'this'設置爲'window'。爲了使它的工作原理相同,你需要在'hideTheButton'調用周圍包裝一個匿名函數並像這樣調用它:'hideTheButton.call(theButton,window.event);' –

+0

非常接近,但是擺脫了事件'匿名處理程序的參數,並將'window.event'傳遞給實際的處理程序。 'attachEvent'不會傳遞一個事件對象。之後,你有我的+1。 :-) –

+1

啊,我看到了,我看到了Dustin Diaz的版本......我使用的第一個版本來自JavaScript Definitive Guide第6版,p。 461 ... –

3
<button onclick="this.style.display='none';">a button</button> 

見例如:http://jsfiddle.net/uWfYk/

+0

如果我已經有一個onclick事件怎麼辦? – user1480167

+1

@ user1480167:只需在該代碼中添加'this.style.display =「none」;'。 –

+0

我的答案使用'attachEvent'或'addEventListener',以便可以使用多個處理程序 –

1

附上onclick事件隱藏和使用JS樣式應用樣式display:none,見下文,

<input type="button" name="btn" value="Hide me" onclick="this.style.display='none'" /> 
0

http://jsfiddle.net/uWfYk/2/

使用jQuery如下

$("#btn").click(function(){ 
    //do need full 
    $(this).fadeOut(); 
})​ 

使用純JS

http://jsfiddle.net/PeM2b/

+0

OP沒有提及使用jQuery,並且您不需要爲簡單任務加載大型DOM庫。 –

+0

這只是一個例子,如何在jQuery中使用它,使用或不使用它取決於開發人員。 –

+0

如果我有多個onclick,我該怎麼辦? – user1480167

相關問題