jquery 将事件添加到面板中的单元格中

jquery add event to cells into a board

如何向图板内的单元格添加事件? 我有一个 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') 中,class 名称应为 .dad-cell

.dad-celldiv,因此他们没有 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');
    }
});

你的$('#dad-board > dad-cell')select或者是错误的, 应该是 $('.dad-board >.dad-row> .dad-cell').

class 应该是 . 而不是 #

A > E只有select第一个child。

Any E element that is a child (i.e. direct descendant) of an A element

A E 可以 select 所有后代,例如 $('.dad-board .dad-cell')

Any E element that is a descendant of an A element (that is: a child, or a child of a child, etc.)