使用 JQuery clone() 时,为什么 remove() 不起作用
when use JQuery clone() , why remove() not working
我使用 jquery clone() 复制 table 元素,我想先删除 td
有我的代码,有人可以帮忙吗?
javascript
$.fn.hasAttr = function(name) {
return this.attr(name) !== undefined;
};
var arr_tr=new Array();
$('table tr').each(function(i){
arr_tr[i].push($(this).clone());
});
//for some reason I need use like below
for(var x in arr_tr){
for(var y in arr_tr[x]){
if(arr_tr[x][y].find('td:eq(0)').hasAttr('rowspan')){//if td has rowspan attribute
arr_tr[x][y].find('td:eq(0)').remove();//<== Why [<td rowspan=3>ABC</td>] can't remove
};
}
}
HTML
<table border=1 width='100%'>
<tr><td rowspan=3>ABC</td><td>A2</td><td>A3</td></tr>
<tr><td>B2</td><td>B3</td></tr>
<tr><td>C2</td><td>C3</td></tr>
</table>
您可以将其简化为仅使用属性选择器:
const $clone = $('table').clone();
$clone.find('td:first-child[rowspan]').remove();
$('#res').append($clone)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border=1 width='100%'>
<tr>
<td rowspan=3>ABC</td>
<td>A2</td>
<td>A3</td>
</tr>
<tr>
<td>B2</td>
<td>B3</td>
</tr>
<tr>
<td>C2</td>
<td>C3</td>
</tr>
<tr>
<td rowspan=2>CDE</td>
<td>C4</td>
<td>C5</td>
</tr>
<tr>
<td>C6</td>
<td>C7</td>
</tr>
</table>
<h3>Result</h3>
<div id="res"></div>
我使用 jquery clone() 复制 table 元素,我想先删除 td 有我的代码,有人可以帮忙吗?
javascript
$.fn.hasAttr = function(name) {
return this.attr(name) !== undefined;
};
var arr_tr=new Array();
$('table tr').each(function(i){
arr_tr[i].push($(this).clone());
});
//for some reason I need use like below
for(var x in arr_tr){
for(var y in arr_tr[x]){
if(arr_tr[x][y].find('td:eq(0)').hasAttr('rowspan')){//if td has rowspan attribute
arr_tr[x][y].find('td:eq(0)').remove();//<== Why [<td rowspan=3>ABC</td>] can't remove
};
}
}
HTML
<table border=1 width='100%'>
<tr><td rowspan=3>ABC</td><td>A2</td><td>A3</td></tr>
<tr><td>B2</td><td>B3</td></tr>
<tr><td>C2</td><td>C3</td></tr>
</table>
您可以将其简化为仅使用属性选择器:
const $clone = $('table').clone();
$clone.find('td:first-child[rowspan]').remove();
$('#res').append($clone)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border=1 width='100%'>
<tr>
<td rowspan=3>ABC</td>
<td>A2</td>
<td>A3</td>
</tr>
<tr>
<td>B2</td>
<td>B3</td>
</tr>
<tr>
<td>C2</td>
<td>C3</td>
</tr>
<tr>
<td rowspan=2>CDE</td>
<td>C4</td>
<td>C5</td>
</tr>
<tr>
<td>C6</td>
<td>C7</td>
</tr>
</table>
<h3>Result</h3>
<div id="res"></div>