在 Javascript 中抽象鼠标点击侦听器
Abstracting the mouse click listener in Javascript
到目前为止,我有类似以下内容,页面上的每个按钮都被赋予一个唯一的 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?
您可以向将应用点击的所有元素添加 class。
$(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>
到目前为止,我有类似以下内容,页面上的每个按钮都被赋予一个唯一的 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?
您可以向将应用点击的所有元素添加 class。
$(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>