2011-02-05 21 views
0

我想在Web窗體上添加三個按鈕。每個按鈕都有自己的ID。當我點擊一個按鈕時,我想讓一個div的內容變得可見,並且讓其他人隱藏起來。但是,現在我使用三個函數作爲事件添加到每個按鈕。有創建一個函數並添加elementId作爲參數的智能方法嗎?我想「陷入」請求對象。如何將按鈕elementId作爲參數捕獲到函數中

function myCoolFunction(parameter) { 
if(parameter=="button1") { 
    hilight("button1"); 
} 
if(parameter=="button2") { 
// do something else for example 
} 

} 

感謝,

+0

你應該使用類似的jQuery這一點。這是一個爲你做這些事情的框架,比如隱藏和全部。 – Marnix 2011-02-05 23:35:36

+1

我正在使用JQuery,我只想變得更加精通JavaScript。 – Shyam 2011-02-05 23:36:31

+0

難道不是`highlight(「div1」)`例如? – 2011-02-05 23:47:34

回答

2

試試這個:

​​
1

使用custom data attributes

標記

<input type="button" value="button one" onClick="myCoolFunction(this)" data-related-div="div_one" /> 
<div id="div_one" /> 
<input type="button" value="button two" onClick="myCoolFunction(this)" data-related-two="div_one"/> 
<div id="div_two" /> 
<input type="button" value="button three" onClick="myCoolFunction(this)" data-related-div="div_three" /> 
<div id="div_three" /> 

腳本

function myCoolFunction(button) { 
    highlight(button.dataset.relatedDiv); 
} 

注意,如果你添加一個新的按鈕,您不必修改JavaScript代碼。

此外,這可能會破壞蹩腳的瀏覽器(例如IE)。只有

dataset屬性是(目前)的Webkit:

更新(對於那些誰沒有按照原來的鏈接)。儘管在所有現代瀏覽器中都可以使用getAttributesetAttribute訪問自定義屬性。

1

如果你有興趣的jQuery ...

HTML

<div id="box_1"></div> 
<div id="box_2"></div> 
<input type="button" data-id="box_1" /> 
<input type="button" data-id="box_2" /> 

JS

$("input:button").click(function(e) { 
    var id = $(this).attr("data-id"), 
    boxes = $(".boxes"), 
    boxes.hide().filter("#"+id).show(); 
    e.preventDefault(); 
}) 
相關問題