考虑以下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>
<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;
id
:$("#follow-user1").click(function(){
alert(1);
});
$("#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;
class
,使用:eq()
选择器:$(".btnFollow:eq(0)").click(function(){
alert(1);
});
$(".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;
以下哪项是最佳做法?是否有更好/更简单的方法来实现这一目标?
答案 0 :(得分:0)
您应该使用data-
属性。
如果您想捕获特定点击次数,可以订阅不同的数据属性:
$('*[data-subscribe-to="mynumber"]');
如果您想使用点击元素中的数据,您可以使用:
$(element).data('subscribe-to');