-2

I am sorry, I am new to javascript.

I want to pass an id selector as a parameter on click event as follows :

i tried :

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

and using jquery :

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


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

can someone please help me to understand where I am going wrong ?

4

3 回答 3

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 结构中删除事件处理程序逻辑。

于 2013-02-22T21:15:07.167 回答
1

do the document.getElementById() call inside the event handler function and pass in the id string

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

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

    // now work with control
}
于 2013-02-22T21:11:54.370 回答
1

<button onclick="mycustomfunction($('#someTextId').val())"/> - this will pass the value. You end up with a string.

<button onclick="mycustomfunction(document.getElementById('someTextId'))"/> - this will pass an object reverence to the DOM element. From here you could do:

mycustomfunction(element) {
    alert(element.value)
}
于 2013-02-22T21:12:07.700 回答