2013-02-22 50 views
-2

對不起,我是JavaScript新手。如何通過單擊事件document.getElementById(「someid」)

我想一個ID選擇通過作爲click事件的參數如下:

我想:

<button onclick="mycustomfunction(document.getElementById('someTextId'))"/> 

和使用jquery:

<button onclick="mycustomfunction($('#someTextId').val())"/> 


mycustomfunction(control) 
{ 
// do something with the control 
} 

有人可以幫我瞭解我要去哪裏錯了?

+0

爲什麼不直接在函數中獲取id? – jchapa 2013-02-22 21:11:17

+0

爲什麼需要將該值傳遞給該函數,因爲該值與該實際被點擊的元素無關? – 2013-02-22 21:11:26

+0

您傳遞的元素不是ID,也缺少'function'關鍵字。 – undefined 2013-02-22 21:11:55

回答

1

document.getElementById()調用事件處理函數內,並通過ID字符串

<button onclick="mycustomfunction('someTextId')"/> 

function mycustomfunction(controlId) { 
    var control = document.getElementById(controlId); 

    // now work with control 
} 
1

<button onclick="mycustomfunction($('#someTextId').val())"/> - 這將傳遞值。你最終得到一個字符串。

<button onclick="mycustomfunction(document.getElementById('someTextId'))"/> - 這會將對象尊敬傳遞給DOM元素。從這裏你可以做到:

mycustomfunction(element) { 
    alert(element.value) 
} 
+0

它在實際事件中執行,而不是頁面加載。 – 2013-02-22 21:16:48

1

你試圖得到的值與被按下的按鈕無關。只是完全刪除的按鈕參考,這樣做:

<button onclick="mycustomfunction()"/> 
<script> 
function myscustomfunction() { 
    var val = $('#someTextId').val(); // must be an input field for val() to work otherwise use html() or text() 
    // do other stuff 
} 
</script> 

或者,如果你真的想使之更jQuery的友好:

<button id="cool_button" /> 
<script> 
$('#cool_button').click(function() { 
    var val = $('#someTextId').val(); // must be an input field for val() to work otherwise use html() or text() 
    // do other stuff 
}); 
</script> 

你會發現,關於jQuery的漂亮的事情之一,如果正確完成,您可以開始從HTML結構中移除事件處理程序邏輯。

+0

我實際上是在for循環中調用它,所以參數有索引,所以我必須使用這種技術 – 2013-02-23 10:54:23

相關問題