For example, the following code creates a link that, when clicked, displays a confirm dialog box. If the user clicks the link and then chooses cancel, the page specified by the link is not loaded.
<A HREF = "http://home.netscape.com/" onClick="return confirm('Load Netscape home page?')">Netscape</A> If the event handler returns false, the default action of the object is canceled as follows:
Note In Navigator 3.0, on some platforms, returning false in an onClick事件适用对象a reset button has no effect.
<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)"> In the preceding example, the keyword this refers to the current object; in this case, the Calculate button. The construct this.form refers to the form containing the button.
For another example, suppose you have created a JavaScript function called pickRandomURL that lets you select a URL at random. You can use onClick to specify a value for the HREF attribute of the A tag dynamically, as shown in the following example:
<A HREF="" onClick="this.href=pickRandomURL()" onMouseOver="window.status='Pick a random URL'; return true">Go!</A> In the above example, onMouseOver specifies a custom message for the browser's status bar when the user places the mouse pointer over the Go! anchor. As this example shows, you must return true to set the window.status property in the onMouseOver event handler.
示例 2: Cancel the checking of a checkbox. The following example creates a checkbox with onClick. The event handler displays a confirm that warns the user that checking the checkbox purges all files. If the user chooses Cancel, onClick returns false and the checkbox is not checked.
<INPUT TYPE="checkbox" NAME="check1" VALUE="check1" onClick="return confirm('This purges all your files. Are you sure?')"> Remove files
要获得关于事件对象的信息,请看事件。
返回页面顶部