到目前为止,我有类似以下内容的内容,其中页面上的每个按钮都有一个唯一的ID(一个,两个,三个等):

$(document).ready(function(){
    $("#one").click(doThing);
    $("#two").click(doThing);
    $("#three").click(doThing);
    $("#four").click(doThing);
});

function doThing(){
    $("#textbox").prepend("<p>Clicked " + this.id + "</p>");
}


有没有一种方法可以压缩越来越多的点击侦听器列表,因此我不必为每个按钮重复自己,而仍然返回适当的ID?

最佳答案

您可以将类添加到将应用点击的所有元素。



$(document).ready(function(){
    $(".do-thing-el").click(function(){
         $("#textbox").prepend("<p>Clicked " + this.id + "</p>");
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="do-thing-el" id="one">Something</p>
<p class="do-thing-el" id="two">Else</p>
<p class="do-thing-el" id="three">Goes</p>
<p class="do-thing-el" id="four">Here</p>
<hr />
<div id="textbox"> <div>

10-04 22:56
查看更多