【发布时间】:2016-04-17 07:55:56
【问题描述】:
我目前正在研究 tictactoe 的 jquery 实现,以便学习 jquery。在我的 html 中,我定义了九个这样的按钮:
<div class="container">
<div class="column-center"><button id="1" style="width: 100px; height: 100px"></button></div>
<div class="column-left"><button id="2" style="width: 100px; height: 100px"></button></div>
<div class="column-right"><button id="3" style="width: 100px; height: 100px"></button></div>
</div>
<div class="container">
<div class="column-center"><button id="4" style="width: 100px; height: 100px"></button></div>
<div class="column-left"><button id="5" style="width: 100px; height: 100px"></button></div>
<div class="column-right"><button id="6" style="width: 100px; height: 100px"></button></div>
</div>
<div class="container">
<div class="column-center"><button id="7" style="width: 100px; height: 100px"></button></div>
<div class="column-left"><button id="8" style="width: 100px; height: 100px"></button></div>
<div class="column-right"><button id="9" style="width: 100px; height: 100px"></button></div>
</div>
在实现 jquery 逻辑时,我认为如果我只为所有这些按钮使用一个侦听器会很好,因为它们都在做同样的事情,我就是这样做的:
$("button").on('click', function () {
if(this.id==1||this.id==2||this.id==3||this.id==4||this.id==5||this.id==6||this.id==7||this.id==8||this.id==9){
$("#"+String(this.id)).css("background-color",$("#color1").css('backgroundColor'));
$("#"+String(this.id)).prop('disabled', true);
//all the other logic here...
}
else if (this.id==startGame) {
//start the Game
}
});
我在这里有三个问题:
性能比为每个按钮使用一个侦听器更差吗?
这样实现监听器是一种好习惯吗?
是否有任何缺点(例如可能发生的一些奇怪的错误)?
【问题讨论】:
-
查看事件委托和事件冒泡。如果你有很多东西要点击,事件委托可以解决这个问题。
-
你也可以...
$('.container').find('button').on('click', function(e) {...或$(document).on('click', '.container button', function(e):) -
做同样的事情。 find 将返回一个 jquery 元素数组并为每个元素绑定一个事件
标签: javascript jquery html performance