Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

php - Can I use Jquery to insert a closing </tr> tag and an opening <tr> tag inside a dynamic table?

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 TR node, problem is, something happens tr isn't closing the tr tag. I'm new to Jquery, is there anything I'm doing wrong with this code?

         <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.min.js" type="text/javascript"></script>
        <script type="text/javascript">
        $(document).ready(function(){
        $('td:nth-child(3n)').after('</tr><tr>');
        });
        </script>

        <table id="mytable" width="266" border="1" cellspacing="10" cellpadding="10">
        <tbody>
          <tr>
        <?php
        function somelongassfunction(){
            return 'Hello';
            }
        function have_products($a){
            return $a<=20;
            }
        $x=0;
        while (have_products($x)) {
            echo '<td>' . somelongassfunction() . '</td>';
            $x++;
        //------------------------------------- 
        /*if (fmod($x,3) == 0) {
                        echo '</tr><tr>';
                        continue;
                        }*/
        //--------------------------------------                    
        if ($x==20){
            break;
            }   
        }   
        ?>
        </tr>
        </tbody>
        </table>    
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...