2016-01-16 23 views
0

我有以下結構的HTML表:如何引用從另一個​​在JQuery中相同<tr>內的一個​​?

<tr> 
    <td>123</td> 
    <td ondblclick="makeeditable(this);">this is some text</td> 
    <td><span ondblclick="makeeditable(this);">this is some more text</span><span>flag</span></td> 
</tr> 

我寫一個jQuery片段,使第二<td>和第三<td>用戶可編輯的第一<span>用雙擊(對於它的價值,該表正在動態生成):

function makeeditable(cell){ 
    var OriginalContent = $(cell).text(); 
    $(cell).html("<input id='editcell' class='input' type='text' value='" + OriginalContent + "' />"); 
    $(cell).children().first().focus(); 
    $(cell).children().first().keypress(function (e) { 
     if (e.which == 13) { 
      var newContent = $(this).val(); 
      $(this).parent().text(newContent); 
     } 
    }); 
    $(cell).children().first().blur(function(){ 
     $(this).parent().text(OriginalContent); 
     $(this).parent().removeClass("cellEditing"); 
    }); 
} 

使用上面的函數,我成功地使單元格可編輯。不過,現在我需要以某種方式檢索剛編輯的單元格的行參考號(第一<td>內的文本,在這個例子中)。我的問題是,怎麼能夠從那個內同一行的另一個<td>一個<span>的同一排和第二<td>的情況下引用行的第一<td>

+1

jQuery有一個兄弟姐妹功能:https://api.jquery.com/siblings/ – tkausl

+1

'變種父母= $(小區).parent( 'TR'); VAR第一= parent.children( 'TD')[0]; first.innerText =「abc」;' – puemos

回答

2

要訪問TDSPAN行中的第一個TD,請使用.closest('tr').find('td:first')

這是你的代碼的簡化版本:

$('.editable ').dblclick(function() { 
 
    var $self= $(this), 
 
     OriginalContent = $(this).text(); 
 

 
    $self.closest('tr').find('td:first').text('Editing'); 
 
    
 
    $self 
 
    .html('<input class="input" type="text" value="' + OriginalContent + '"/>') 
 
    .find('input')  //the following methods now refer to the new input 
 
    .focus() 
 
    .keypress(function(e) { 
 
     if (e.which === 13) { 
 
     $self.text($(this).val()); 
 
     } 
 
    }) 
 
    .blur(function() { 
 
     $self.closest('tr').find('td:first').text('Double-click to edit'); 
 
    
 
     $self 
 
     .text(OriginalContent) 
 
    }); 
 
});
td { 
 
    border: 1px solid #ddd; 
 
} 
 

 
.editable { 
 
    background: yellow; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tr> 
 
    <td>Double-click to edit</td> 
 
    <td class="editable">this is some text</td> 
 
    <td><span class="editable">this is some more text</span><span>flag</span> 
 
    </td> 
 
    </tr> 
 
</table>

1
var parent = $(cell).parent(); 
while(parent.get(0).tagName != "TR") 
    parent = parent.parent(); 
var referenceLine = parent.children('td')[0]; 

// here is your reference 
console.log(referenceLine.innerText); 

只是想補充一點,裏克·希區柯克的回答是好,很好實現,但.parent()和。孩子()方法比.closest快3倍以上()和.find()方法:check here and run the test

相關問題