2012-08-03 21 views
1

簡單的任務在這裏,但我不明白:如果單擊表格單元格,我需要檢查它是否包含input字段或不。如果不存在,應該創建一個新的。jQuery - 如何檢查輸入是否存在?

到目前爲止,我得到這個:

$("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){...},但都失敗了。那麼我該如何做對?什麼是正確的方式來檢查單擊的單元格是否包含輸入字段?

回答

9

像下面的內容將工作

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

$this是一個jQuery對象,它封裝了當前<td>元素(由this引用),所以我們需要尋找到DOM中的這個元素,看它是否包含一個<input>元素。如果是這樣,.length屬性將大於0,因此是一個真值。

0

嘗試:

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

    var newInput = $(document.createElement("input")).attr("class", "input-small"); 
     $this.append(newInput); 
} 
0
if ($(this).children("input").length == 0) //the cell doesn't contain any input elements. 
1

拉斯凸輪已經爲你的答案(!給予好評他),我只是想幫助你優化代碼的一些東西。

// .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); 
    } 
}); 

編輯:固定邏輯

+0

謝謝你的評論代碼!將newInput修正爲'$('');'它幾乎奏效。問題是我不得不像'if($ this.find('input')。length == false)'這樣做,否則它不起作用。有什麼理由呢? (因爲你寫的對我來說聽起來合乎邏輯!) – Sven 2012-08-03 10:48:15

+0

看起來很奇怪,肯定有沒有錯別的地方? 我在這裏做了一個fidde http://jsfiddle.net/LxHK9/,在那裏你可以看到它的行動。如果(!$ this.find('input').length) 因爲它現在檢查它是否存在,然後附加它,所以它應該爲 。而不是相反。 – ninja 2012-08-03 10:53:39

+0

哈哈耶,似乎是我身邊的邏輯錯誤! 'if($ this.find('input').length){...}' - 這意味着有輸入。所以如果我把'newInput.appendTo($ this);'這對我的目的來說基本沒有意義。但是,如果 - 否則它就像一個魅力! :) – Sven 2012-08-03 10:57:03