Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
对多个按钮的操作-JQuery_Jquery - Fatal编程技术网

对多个按钮的操作-JQuery

对多个按钮的操作-JQuery,jquery,Jquery,我需要写一个在button1和button2上工作的函数。我点击button1,我可以隐藏t,但是我如何为button2添加相同的函数呢 <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script> <script>

我需要写一个在button1和button2上工作的函数。我点击button1,我可以隐藏t,但是我如何为button2添加相同的函数呢

<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>

由于您的事件处理程序已经使用它来引用触发事件的任何元素,即在本例中,已单击的元素,因此您只需要将选择器泛化为$以包含button2。这取决于您的标记,但目前您可以使用:

$("#button1, #button2").click(function () {
    $(this).hide();
});
演示:

$("#button1, #button2").click(function () {
    $(this).hide();
});