将参数传递给事件处理程序的最佳做法是什么?

时间:2016-02-21 17:05:15

标签: javascript jquery html javascript-events jquery-selectors

考虑以下HTML块:

<button id="follow-user1" class="btnFollow">Follow User1</button>
<button id="follow-user2" class="btnFollow">Follow User2</button>
<button id="follow-user3" class="btnFollow">Follow User3</button>
<button id="follow-user4" class="btnFollow">Follow User4</button>

我可以通过多种方法将事件处理程序绑定到每个按钮:

通过onclick="code()"(不良做法):

<button id="follow-user1" class="btnFollow" onclick="alert(1)">Follow User1</button>

&#13;
&#13;
<button id="follow-user1" class="btnFollow" onclick="alert(1)">Follow User1</button>
<button id="follow-user2" class="btnFollow" onclick="alert(1)">Follow User2</button>
<button id="follow-user3" class="btnFollow" onclick="alert(1)">Follow User3</button>
<button id="follow-user4" class="btnFollow" onclick="alert(1)">Follow User4</button>
&#13;
&#13;
&#13;

通过元素的id

$("#follow-user1").click(function(){
 alert(1);
});

&#13;
&#13;
$("#follow-user1").click(function(){
  alert(1);
});
$("#follow-user2").click(function(){
  alert(2);
});
$("#follow-user3").click(function(){
  alert(3);
});
$("#follow-user4").click(function(){
  alert(4);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="follow-user1" class="btnFollow">Follow User1</button>
<button id="follow-user2" class="btnFollow">Follow User2</button>
<button id="follow-user3" class="btnFollow">Follow User3</button>
<button id="follow-user4" class="btnFollow">Follow User4</button>
&#13;
&#13;
&#13;

通过元素的class,使用:eq()选择器:

$(".btnFollow:eq(0)").click(function(){
 alert(1);
});

&#13;
&#13;
$(".btnFollow:eq(0)").click(function() {
  alert(1);
});
$(".btnFollow:eq(1)").click(function() {
  alert(2);
});
$(".btnFollow:eq(2)").click(function() {
  alert(3);
});
$(".btnFollow:eq(3)").click(function() {
  alert(4);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="follow-user1" class="btnFollow">Follow User1</button>
<button id="follow-user2" class="btnFollow">Follow User2</button>
<button id="follow-user3" class="btnFollow">Follow User3</button>
<button id="follow-user4" class="btnFollow">Follow User4</button>
&#13;
&#13;
&#13;

以下哪项是最佳做法?是否有更好/更简单的方法来实现这一目标?

1 个答案:

答案 0 :(得分:0)

您应该使用data-属性。

如果您想捕获特定点击次数,可以订阅不同的数据属性:

$('*[data-subscribe-to="mynumber"]');

如果您想使用点击元素中的数据,您可以使用:

$(element).data('subscribe-to');