문제

I have the following table structure.

<table>
    <tr>
        <td>ASDF</td>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
    </tr>
    <tr>
        <td>ASDF</td>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
    </tr>
</table>

What I need to do clone all the cells with a class of "selectable", AND it's immediate previous sibling, and insert the clones in a new row. In other words, i need the result to be:

<table>
    <tr>
        <td>ASDF</td>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
    </tr>
    <tr>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
    </tr>
    <tr>
        <td>ASDF</td>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
        <td>ASDF</td>
    </tr>
    <tr>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
        <td>ASDF</td>
        <td class="selectable">ASDF</td>
    </tr>
</table>

I can successfully clone the cells with a class of "selectable" by using the following. (I know this isn't valid markup as the 'TR' tags are missing. Just trying to shorten my example as much as possible.)

$('tr').each(function(){
    $(this).after($(this).find('td.selectable').clone());
})

However, I cannot work out how to include the previous sibling in the clone as well.

Can anyone point me in the right direction?

Thanks

도움이 되었습니까?

해결책

You can use prev() to get the previous sibling, and then addBack() to merge the two together. To insert the new row, just create it, and append the merged collection to it by using append():

$(this).after( $('<tr>').append( $(this).find('td.selectable').prev().addBack().clone() ) );

Here's a fiddle

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top