我的代码中有什么错误?如果它是空的,则删除下一个td元素。我正在努力解决这个问题。
$(document).on("click", ".expand_img" , function(e ) {
var ColsCount =$(this).parents('td').next('td').length;
var counter =0;
var nextCols = $(this).parents('td').next('td');
if (nextCols.contents().length == 0) {
$(this).hide(); }
var next = $(this).parents('td').next('td');
if ((next.contents().length == 0) && ($(this).parents('td').next('td').length==1)){
next.remove();
}
if (ColsCount!="") {
$(this).parents('td').attr('colSpan', '' + parseInt(ColsCount + 1,10) + '')
}
else if(ColsCount=="") {
counter = 1;
}
});
我的HTML代码在这里
<tr>
<td class="ui-droppable ui-sortable content" colspan="1"></td>
<td class="ui-droppable ui-sortable content" colspan="1">
<span>
<img src="images/Close-icon.png" class="close_img">
<img src="images/expand.png" class="expand_img">iPod
</span></td>
<td class="ui-droppable ui-sortable content" colspan="1"></td>
<td class="ui-droppable ui-sortable content" colspan="1"></td>
<td class="ui-droppable ui-sortable content" colspan="1"></td>
</tr>
答案 0 :(得分:1)
使用.parent()
访问元素的父级而非.parents('td')
。
在您的代码中,您访问的是错误的父级。 .parent()
将为您提供<span>
,.parent().parent()
将为您提供所需的<td>
。
工作代码段:
$(document).on("click", ".expand_img" , function(e ) {
var ColsCount =$(this).parents('td').next('td').length;
var counter =0;
var nextCols = $(this).parent().parent().next('td');
if (nextCols.contents().length == 0) {
$(this).hide(); }
var next = $(this).parents('td').next('td');
if ((next.contents().length == 0) && ($(this).parent().parent().next('td').length==1)){
next.remove();
}
if (ColsCount!="") {
$(this).parents('td').attr('colSpan', '' + parseInt(ColsCount + 1,10) + '')
}
else if(ColsCount=="") {
counter = 1;
}
});
&#13;
table, tr, td{
border: 1px solid black;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="ui-droppable ui-sortable content" colspan="1"></td>
<td class="ui-droppable ui-sortable content" colspan="1">
<span>
<img src="images/Close-icon.png" class="close_img">
<img src="images/expand.png" class="expand_img">
iPod
</span>
</td>
<td class="ui-droppable ui-sortable content" colspan="1"></td>
<td class="ui-droppable ui-sortable content" colspan="1"></td>
<td class="ui-droppable ui-sortable content" colspan="1"></td>
</tr>
</table>
&#13;
答案 1 :(得分:1)
使用 closest() 查找closest td
g expand_im
var nextCols = $(this).closest("td").next('td');
答案 2 :(得分:1)
试试这个:
$(document).on("click", ".expand_img" , function(e ) {
var colsSpan = 0;
var $parentTD = $(this).closest('td');//get parent td of image clicked
//iterate through next td
while($parentTD.next('td').length > 0)
{
var $nextTD = $parentTD.next('td');
if($nextTD.contents().length == 0)
{
$nextTD.remove();
colsSpan++;
}
else
{
//shift to next to parent td
$parentTD = $nextTD;
}
}
if(colsSpan > 0)
$(this).closest('td').attr('colSpan',colsSpan);
});