1

我刚刚开始使用 JavaScript,我想知道如何让不同的按钮做不同的事情。到目前为止,我可以让一个按钮做一件事,但是如何让第二个按钮做不同的事情呢?这是编码:

<html>
<head>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("Your Name");
if (name!=null && name!="")
  {
  alert("Thanks for clicking " + name + "!");
  window.top.location.replace("http://www.google.com");
  }
}
</script>
</head>
<body>
<ul>
<li>
<input type="button" onclick="show_prompt()" value="Button One" />
</ul>
</body>
</html>
4

4 回答 4

1

我猜你的意思是喜欢用不同的按钮做不同的事情,但使用相同的功能:

JavaScript:

function myFunction(str) {
    if(str.length > 3){
        alert("big");
    }else{
        alert("small");
    }
}

HTML:

<input type="button" onclick="myFunction('test');" value="Button 1" />
<input type="button" onclick="myFunction('hi');" value="Button 2" />

如果我的假设是错误的,只需创建不同的功能并onclick用它们各自的功能替换按钮

于 2012-04-12T02:36:45.980 回答
0

定义另一个函数并将第二个按钮绑定到它!

function alert_hi() {
    alert("Hi!");
}

<input type="button" onclick="alert_hi()" value="Button Two" />

如果这引起了您的兴趣,我强烈推荐Eloquent Javascript

于 2012-04-12T02:27:07.983 回答
0

让第二个按钮做某事与让第一个按钮做某事基本相同。它只是两个功能和两个按钮。我想这就是你要问的。

<html>
    <head>
    <script type="text/javascript">
        function doSomething()
        {
           // Do something when button one is clicked
        }

        function doSomethingElse() 
        {
           // Do something else when button two is clicked
        }
    </script>
</head>
<body>
    <input type="button" onclick="doSomething()" value="Button One" />
    <input type="button" onclick="doSomethingElse()" value="Button Two" />
</body>
</html>
于 2012-04-12T02:29:48.270 回答
0

如果您认真学习……您可以阅读有关事件注册模型的信息。

在你的例子中。

js

var btn1 = document.getElementById('btn1'),
    btn2 = document.getElementById('btn2');
btn1.addEventListener('click', show_me, false); // i am not IE friendly
btn2.addEventListener('click', show_me, false); // you can replace show_me with any function you would like.
function show_me() {
    alert(this.value + ' was clicked'); // this references the element which the click event was invoked on.
}

html

<input type="button" id="btn1" value="Button One" />
<input type="button" id="btn2" value="Button Two" />
于 2012-04-12T02:33:52.747 回答