如何将事件添加到板上的单元格?
我有一个9x9的网格,我想向他们添加一个事件,例如,这是我的HTML网格的一部分:
<div class="container">
<div class="dad-board">
<div class="dad-row">
<div class="dad-cell">
<input type="number" data-column="0" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="1" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="2" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="3" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="4" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="5" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="6" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="7" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="8" data-line="0">
</div>
...
</div>
</div>
现在在jQuery中,我想做这样的事情:
(function() {
'use strict'
$('#dad-board > dad-cell').focusout(function(){
if($(this).text()>0 && $(this).text()<10){
$(this).addClass('with-value');
}else{
$(this).removeClass('with-value');
}
});
}());
最佳答案
两件事情:
在$('#dad-board > dad-cell')
中,类名称应为.dad-cell
。.dad-cell
是div
,因此它们没有focusout
事件。我认为您的意思是$('#dad-board > .dad-cell input')
。
为了使您当前的代码正常工作,您还必须进行一些调整:
$('#dad-board > .dad-cell input').focusout(function(){
//as we're talking about input fields, the value is read with val(), not text()
//and as you're gonna evaluate it as an integer, lets convert the value to integer
var value=parseInt($(this).val());
if(!isNaN(value)&&value>0 && value<10){
//you might want to set with-value to the <div>, not the input
$(this).parent().addClass('with-value');
}else{
//you might want to set with-value to the <div>, not the input
$(this).parent().removeClass('with-value');
}
});