1

ここでの簡単なタスクですが、正しく理解できません。テーブル セルがクリックされた場合、inputフィールドが含まれているかどうかを確認する必要があります。そこにない場合は、新しいものを作成する必要があります。

これまでのところ、私はこれを得ました:

$("tbody td").bind("click", function(){
  $this = $(this);
  var newInput = $(document.createElement("input")).attr("class", "input-small");
  $this.append(newInput);
})

これは機能しますが、ご覧のとおり、入力が既に存在する場合はテストに失敗します。を含むさまざまな方法をすでに試しましif($this.text.length){...}if($this.val().hasClass("input-small") == true){...}が、すべて失敗します。では、どうすれば正しくできますか?クリックしたセルに入力フィールドが含まれているかどうかを確認する正しい方法は何ですか?

4

4 に答える 4

11

次のようなものが機能します

if ($this.find('input').length) { 
    // the td clicked contains an <input>
}

$this<td>は現在の要素(によって参照される)をラップするjQueryオブジェクトであるthisため、DOMでこの要素を調べて、要素が含まれているかどうかを確認する必要があり<input>ます。含まれている場合、.lengthプロパティは0より大きくなるため、真の値になります。

于 2012-08-03T10:19:36.673 に答える
1

Russ Cam が答えを教えてくれます (彼に賛成票を投じてください!)。

// .click just points to jquerys .on function, so calling it directly is faster.
$('tbody td').on('click', function() {
     // always declare your variables properly, some javascript engines could have issues, however excellent that you are caching $(this)
     var $this = $(this),
         newInput = $('<input class="input-small"');

     // .lenght will return false if the length is 0, so no need to compare it to an int
     if(!$this.find('input').length) {
         newInput.appendTo($this);
     }
});

編集:固定ロジック

于 2012-08-03T10:27:05.257 に答える
0

試す:

if($(this).find('input').length > 0){

    var newInput = $(document.createElement("input")).attr("class", "input-small");
      $this.append(newInput);
}
于 2012-08-03T10:20:54.967 に答える
0
if ($(this).children("input").length == 0) //the cell doesn't contain any input elements.
于 2012-08-03T10:21:36.517 に答える