开发者

What is 'click()' in JavaScript

开发者 https://www.devze.com 2022-12-19 11:16 出处:网络
I was playing around with JavaScript in FireFox, and hit a problem that is illustrated in the following example:

I was playing around with JavaScript in FireFox, and hit a problem that is illustrated in the following example:

<HEAD>
<script type="text/javascript">
function click()
{
    alert("click");
}

</script>
</HEAD>

<BODY>

<in开发者_开发技巧put type="radio" onclick="click()">
</BODY>

When I click on the radio button, nothing happens, and no errors (in Firebug)

If I change the name of the function to do_click, and change the onclick, then I get the alert.

So question is: what is happening? click does not appear to be a reserved word, or an existing symbol


Code within inline event handlers is scoped to the element, as if it was in a with block.

Therefore, within the onclick handler, the name click resolves to the element's click method.

This can be demonstrated by writing alert(nodeName) in the handler


DOM elements have a native click() method.

The following will show that click is a native method:

<input type="radio" onclick="alert(click.toString())">

You can register your click function as the event handler as follows. Within the handler, this will refer to the HTML element.

<input type="radio" id="foo" >

function click()
{
    alert("click");
}
document.getElementById('foo').onclick = click;

There is an excellent series of articles about browser events at http://www.quirksmode.org/js/introevents.html


I think click() is a reserved procedure name, so you can't overwrite it. Explains why changing the name and nothing else gets it working.


I think the click() method in javascript simulates clicking the button. So this must be a sort of infinite loop...

Edited to add: Check out MSDN for documentation of the click method


'click' by itself is NOT a javascript reserved keyword outside the context of the inline event handler as Slaks answered.

That is to say the "click" method defined in the question is valid. Attaching the event handler 'externally' will work. E.g. using jQuery:

$('input').click(click);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号