在JQuery中访问两个不同的按钮

时间:2013-04-15 20:29:30

标签: javascript jquery html5

我是网络开发的新手,我现在正在学习JQuery。我在这里有疑问。这是来自W3Schools.com的代码。我想知道如果我在这里再添加一个按钮,我怎么能只为FIRST按钮的click事件运行这个JavaScript。

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").hide();
  });
});
</script>
</head>

<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
<br />
<button>Second Button</button>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

您可以在按钮上添加ID,并通过选择这样的ID(如果按钮ID为'submitForm')$("#submitForm")

将Click事件放在该ID上

事实上,有很多方法可以用jquery选择元素,请查看:http://api.jquery.com/category/selectors/

在您的具体示例中,如果您不想在按钮上添加ID,您可以使用:首先只访问第一个,例如$("button:first")

答案 1 :(得分:1)

更改

  $("button").click(function(){
    $("p").hide();
  });

  $("button").eq(0).click(function(){
    $("p").hide();
  });

这只会绑定到第一个按钮的click事件。请参阅http://api.jquery.com/eq/

<强> jsFiddle example