我需要编写一个适用于button1和button2的函数。我单击按钮 1,我可以隐藏 t,但我如何为按钮 2 添加相同的功能?
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#button1").click(function(){
$(this).hide();
});
});
</script>
</head>
<body>
<button id="button1">Button1</button>
<button id="button2">Button2</button>
</body>
</html>
只需将其添加到选择器:
$(document).ready(function(){
$("#button1, #button2").click(function(){
$(this).hide();
});
});
添加一个类而不是使用 id 作为标识符,然后将您的类应用于您希望具有相同操作的所有元素。
<button class="yourbuttons" id="button1">Button1</button>
<button class="yourbuttons" id="button2">Button2</button>
然后:
$(".yourbuttons").click(function(){
$(this).hide();
});
由于您的事件处理程序已经使用 this
来引用触发事件的任何元素(即在本例中,已被单击),因此您只需通用化您放入$()
的选择器即可包含#button2
。这将取决于您的标记,但就目前而言,您可以使用:
$("#button1, #button2").click(function () {
$(this).hide();
});
演示:http://jsfiddle.net/BByTB/