2013-02-22 49 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

相关问题