Can I use Jquery to insert a closing tag and an opening tag inside a dynamic table?

前端 未结 3 834
小蘑菇
小蘑菇 2020-12-21 06:43

I\'m trying to use the code below to dynamically add closing tag followed by opening so that i creates a new row every three cells. Almost working, DOM inspector shows a T

相关标签:
3条回答
  • 2020-12-21 07:01

    As lonesomeday said, you can't treat a DOM like a bit of HTML. Besides, TR closing tags are optional so when you insert some markup with an opening TR, the browser will close it. You don't need a closing tag.

    0 讨论(0)
  • 2020-12-21 07:07

    Another approach is to detach all the td elements, and then split them into groups of 3 using splice:

    var td = $('tr td').detach();
    $('tr').remove();
    while(td.length>0){ 
     $(td.splice(0,3)).wrapAll('<tr />').parent().appendTo('tbody');   
    }
    

    example: http://jsfiddle.net/niklasvh/C6unV/

    0 讨论(0)
  • 2020-12-21 07:15

    You can't work on a DOM selection as if it was an HTML document. A DOM document is a hierarchy of nodes, not of tags. The tags in your HTML are parsed into a DOM document by the browser. You can't then add a single bit of HTML and then expect it to be parsed back into a DOM structure.

    Instead, you'll need to do the wrapping in jQuery. This is a viable approach -- it may not be the most efficient.

    $('td').each(function(idx) {
        if (idx % 3) {
            return;
        } else {
            $(this).nextAll(':lt(2)').andSelf().wrapAll('<tr/>');
        }
    }).parent().unwrap();
    

    jsFiddle

    0 讨论(0)
提交回复
热议问题