JavaScript in 10 Steps or Less

本文介绍了一种使用JavaScript为网页元素添加交互性的方法。通过创建一个简单的函数并在HTML链接中调用该函数,可以轻松实现点击链接时弹出对话框的效果。文章提供了两种调用函数的方法:一是使用`onClick`属性,二是利用`javascript:`伪协议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

没有按别人的推荐,学什么圣经类的js书,而是随便挑了本《JavaScript in 10 Steps or Less》。

花了3个小时,看了30个task。

讲的非常浅显详细。虽然是E文,但很浅显易懂。

 

task31:

Calling Functions from Tags


One of the benefits of JavaScript is to be able to tie interactivity to elements of the HTML page. One way you can do this is to set up links in HTML that actually trigger calls to JavaScript functions when the link is clicked.


There are two ways to do this:
1. Use the onClick attribute of the a tag to call the function:
<a href=”#” onClick=”functionName()”>Link text</a>
2. Use a javascript: URL in the href attribute of the a tag to call
the function:
<a href=”javascript:functionName()”>Link text</a>


The following task illustrates these two methods of calling a function from a link by creating a function that displays an alert dialog box to the user and then providing two separate links for the user to use to call the function:
1. Open a new HTML document in your preferred HTML or text editor.
2. Create the header of the document with opening and closing head tags:
<head>
</head>
3. Insert a script block in the header of the document:
<script language=”JavaScript”>
<!--
// -->
</script>
4. Create a function named hello that takes no arguments:
function hello() {
}
5. In the function, use the window.alert method to display an alert
dialog box:
window.alert(“Hello”);
6. Create the body of the document with opening and closing body tags.
7. In the final page create two links that call the hello function using
onClick and the javascript: URL techniques so that the final
page looks like Listing 31-1.
<head>
<script language=”JavaScript”>
<!--
function hello() {
window.alert(“Hello”);
}
// -->
</script>
</head>
<body>
<a href=”#” onClick=”hello();”>Call hello() from
onClick.</a>
<br>
<a href=”javascript:hello();”>Cal hello() from href.</a>
</body>
Listing 31-1: Calling a function from a link.
8. Save the file.
9. Open the file in a browser, and you should see two links in the
browser.
10. Click on either link and you should see a dialog box.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值