javascript - 使用 PHP/Javascript 中的按钮动态生成 <div> 部分?

标签 javascript php jquery mysql ajax

大家好,我有一个代码,我想要在 div 内,并且我想在单击“添加部分”按钮时生成 1 by 1。这是我的代码

带有 JavaScript 代码的surveycontent.php

<div id="sform" class="tab-pane fade">

             <br>

                <div class="col-md-12">
                <div class="col-md-10" id="sections">
               <div class="panel-group">
    <div class="panel panel-default">
      <div class="panel-heading">Section 1</div>
      <div class="panel-body">


        <b>Number of Questions: </b>


                <span id="ctr_num"> <input id="q_num" class="form-control" style="width:50px;" name="q_num" size="2" placeholder="#"/></span>
                <br>


                 <b>Select Category</b>


                <select class="form-control" style="width: 150px;" id="categorydd" name="catdd" onChange="change_category()">

                    <option>-Please Select One-</option>

                    <?php
                    $query=mysqli_query($con, "SELECT category_id, categoryname FROM category WHERE ParentCategoryID IS NULL");
                    while($row=mysqli_fetch_array($query)) {
                        ?>
                        <option value="<?php echo $row["category_id"]; ?>"><?php echo $row["categoryname"]; ?></option>

                        <?php
                    }
                    ?>

                </select><br>
            <b>Select Subcategory</b>

                <div id="subcategory">

                    <select class="form-control" style="width: 150px;">

                        <option>-Please Select One-</option>

                    </select><br/>

                </div>



        <p hidden>Select Questions</p>

         </br>

                <div id="question">



                </div>      <br/>





            </div>
            </div>
    </div>
                </div>
                </div>
             </div>



    <hr>



       <div class="col-md-2">
       <input type="submit" name="addsection" class="btn btn-default" value="Add Section" id="addsection" />

       </div>
</div>

    <script>
      function change_category()
        {
            var xmlhttp=new XMLHttpRequest();
            xmlhttp.open("GET","ajax.php?category="+document.getElementById("categorydd").value,false);
            xmlhttp.send(null);
            document.getElementById("subcategory").innerHTML=xmlhttp.responseText;


            if(document.getElementById("categorydd").value=="Select")
            {
            document.getElementById("question").innerHTML="<select><option>Select</option></select>";
            }

            //alert(document.getElementById("categorydd").value);
            var xmlhttp=new XMLHttpRequest();
            xmlhttp.open("GET","ajax.php?main=1&subcategory="+document.getElementById("categorydd").value +"&cnt="+document.getElementById("q_num").value,false);
            xmlhttp.send(null);
            document.getElementById("question").innerHTML=xmlhttp.responseText;
        }


        function load_questions(){

            var xmlhttp=new XMLHttpRequest();
            xmlhttp.open("GET","ajax.php??main=1&subcategory="+document.getElementById("subcategorydd").value +"&cnt="+document.getElementById("q_num").value,false);
            xmlhttp.send(null);
            document.getElementById("question").innerHTML=xmlhttp.responseText;


        }

添加部分按钮的 JavaScript 代码

 <script>
        $(document).ready(function(){
            var ctr = 0;
            $("#addsection").click(function(){
                 var section = document.getElementById("sections").innerHTML;
                $("#sections").append(section);


                ctr++;


            });

        });
    </script>

我认为这是错误的,因为我有 atm 的这段代码只会使它变得错误,就像我生成 1 个部分,并在下拉列表中为添加的部分选择一个数据一样,它会对第一个部分执行相同的操作,就像它复制您在一个部分中移动的内容一样。这是一个创作调查系统,这是添加栏目的部分。

这些类别、子类别、问题下拉列表背后的代码。

ajax.php

if($category!=""){

    $query=mysqli_query($con, "SELECT category_id, categoryname FROM category WHERE ParentCategoryID =$category ");
    echo "<select id='subcategorydd' class='form-control' style='width:150px;' name='subcatdd' onchange='load_questions()' >";
    echo "<option selected>"; echo "Select"; echo "</option>";
    while($row=mysqli_fetch_array($query))
    {
        echo "<option value='$row[category_id]'>"; echo $row["categoryname"]; echo "</option>";
    }
    echo "</select>";
}

// for loading ques under Category already
if($question !="" && $cnt!="" && $addQues!="yes" && $main == 1){
    $i = 0;
    for( $i = 1; $i <= $cnt; $i++ ){
        $query=mysqli_query($con, "SELECT question.* FROM question LEFT JOIN category AS subcategory on subcategory.category_id = question.question_subcat WHERE question.question_category = $question AND (question.question_subcat IS NULL OR subcategory.category_id IS NOT NULL)");


        echo "<form>
        <b id='labelquestion_dropdown{$i}'>Question #{$i}</b>
        <select id='question_dropdown{$i}' class='form-control' onchange=\"showUser( this.value, 'txtHint{$i}' )\" style='width: 300px;' name='question_dropdowns{$i}'>
            <option selected>Select";

        while($row=mysqli_fetch_array($query)){
            echo "<option value='{$row['question_id']}'>" . $row["questiontitle"];
        }

        echo "
        </select>
    </form>
    <div id='txtHint{$i}'><b>Person info will be listed here...</b></div>
    <br />";
    }
    echo "<div id='insertQuesHere".$i."'></div>";

    echo "<a href='#add_question' onclick='return addQues_Cat();'>Add Question</a> | ";
    echo "<a href='#del_question' onclick='return delQues();'>Delete Question</a>";
}

// for loading ques under SUBCATEGORY
if($question !="" && $cnt!="" && $addQues!="yes" && $main != 1){
    $i = 0;
    for ($i = 1; $i <= $cnt; $i++)
    {
        $query=mysqli_query($con, "SELECT * FROM question WHERE question_subcat = $question ");
        echo "
    <form>
        <b id='labelquestion_dropdown{$i}'>Question #{$i}</b>
        <select id='question_dropdown{$i}' class='form-control' onchange=\"showUser( this.value, 'txtHint{$i}' )\" style='width: 300px;' name='question_dropdowns{$i}'>
     <option selected>Select";
        while($row=mysqli_fetch_array($query))
        {
            echo "<option value='{$row['question_id']}'>" . $row["questiontitle"];
        }

        echo "
        </select>
    </form>
    <div id='txtHint{$i}'><b>Person info will be listed here...</b></div>  
    <br />";
    }

    echo "<div id='insertQuesHere".$i."'></div>     ";

    echo "<a href='#add_question' onclick='return addQues();'>Add Question</a> | ";
    echo "<a href='#del_question' onclick='return delQues();'>Delete Question</a>";
}

最佳答案

我认为 HTML 标记也许应该更像这样。如果您在执行过程中正确缩进代码,您通常会发现发现问题要容易得多。

互联网上有几个网站可以帮助处理代码缩进 - for example您可以使用其他服务验证您的页面,例如 W3C Markup Validator

<div id='sform' class='tab-pane fade'>
    <br />
    <div class='col-md-12'>
        <div class='col-md-10' id='sections'>
            <div class='panel-group'>
                <div class='panel panel-default'>
                    <div class='panel-heading'>Section 1</div>
                    <div class='panel-body'>
                        <b>Number of Questions: </b>
                        <span id='ctr_num'> <input id='q_num' class='form-control' style='width:50px;' name='q_num' size='2' placeholder='#'/></span>
                        <br />
                        <b>Select Category</b>
                        <select class='form-control' style='width: 150px;' id='categorydd' name='catdd' onChange='change_category()'>
                            <option>-Please Select One-</option>
                            <?php
                                $query=mysqli_query($con, 'SELECT `category_id`, `categoryname` FROM `category` WHERE `ParentCategoryID` IS NULL');
                                while( $row=mysqli_fetch_array($query) ) {
                            ?>
                            <option value='<?php echo $row['category_id']; ?>'><?php echo $row['categoryname']; ?></option>
                            <?php
                                }
                            ?>
                        </select>
                        <br />
                        <b>Select Subcategory</b>
                        <div id='subcategory'>
                            <select class='form-control' style='width: 150px;'>
                                <option>-Please Select One-</option>
                            </select>
                            <br />
                        </div>
                        <p hidden>Select Questions</p>
                        <br />
                        <div id='question'>
                        </div>
                        <br />
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<hr>
<div class='col-md-2'>
    <input type='submit' name='addsection' class='btn btn-default' value='Add Section' id='addsection' />
</div>

我不知道这是否有帮助,或者我是否确实正确理解了问题(单击按钮时有效克隆该部分的内容?)

以下内容克隆了整个部分(无需担心 ID 属性,但会有重复的名称),因此需要做更多工作才能使新克隆在 DOM 中唯一并更改部分标题/部分数量。

复制并运行代码(如发布的那样),看看它是否或多或少地完成了您想要做的事情。 ajax 代码不会执行原始代码中的所有任务 - 例如设置问题

的内容
<?php
    session_start();
    /* to emulate the ajax request that is sent by change_category() */
    if( $_SERVER['REQUEST_METHOD']=='POST' ){

        if( !empty( $_POST['action'] ) && $_POST['action']=='changecat' ){
            ob_clean();
            for( $i=0; $i < 10; $i++ )echo "<option value='$i'>Choice - $i";
            exit();
        }

    }
?>
<!doctype html>
<html>
    <head>
        <title>Cloning a section of the HTML page</title>
        <style></style>
        <script>
            function ajax(m,u,p,c,o){
                /*
                    m=Method,
                    u=Url,
                    p=Params,
                    c=Callback,
                    o=Options
                */
                var xhr=new XMLHttpRequest();
                xhr.onreadystatechange=function(){
                    if( xhr.readyState==4 && xhr.status==200 ){
                        /*
                            The callback takes 3 arguments
                            ------------------------------
                            r=xhr.response
                            o=options ( as supplied to ajax function )
                            h=response headers
                        */
                        c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
                    }
                };
                var params=[];
                for( var n in p )params.push(n+'='+p[n]);

                switch( m.toLowerCase() ){
                    case 'post': p=params.join('&'); break;
                    case 'get': u+='?'+params.join('&'); p=null; break;
                }
                xhr.open( m.toUpperCase(), u, true );
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xhr.send( p );
            }

            function change_category(evt){
                var el=evt.target;
                console.log('ajax function to get contents of dropdown - '+el.value+' & append returned data to subcategory?' );

                var method='post';

                var url=location.href;

                var params={
                    action:'changecat'
                };

                var callback=function(r,o,h){
                    var col=el.parentNode.querySelectorAll('select.subcategory');
                    if( col.length==1 )col[0].innerHTML=r;
                    col=el.parentNode.querySelectorAll('div.question');
                    if( col.length==1 )col[0].innerHTML='Some question - relating to Select:'+el.tagName+', Name:'+el.name+', Option:'+el.value+', chose from the database, goes here I believe?';
                }.bind( this );

                var options={};

                ajax.call( this, method, url, params, callback, options );
            }

            function clone_section(e){
                e.preventDefault();
                var parent=document.getElementById('clone-parent');
                var col=parent.querySelectorAll('div.clone-section');
                var section=col[ col.length-1 ];
                var clone=section.cloneNode( true );

                /* change the heading */
                var heading=clone.querySelectorAll('div.panel-heading')[0];
                var regex=/(\d+)/gi;
                var matches=heading.innerHTML.match( regex );
                var i=parseInt( matches[0] );
                heading.innerHTML=heading.innerHTML.replace( i, i + 1 );

                /* make changes to the various cloned elements */
                var q_num=clone.querySelectorAll('input[name^="q_num_"]')[0];
                var matches=q_num.name.match( regex );
                var i=parseInt( matches[0] );
                q_num.name = q_num.name.replace(i,i+1);
                q_num.value='';

                var cat=clone.querySelectorAll('select[name^="catdd_"]')[0];
                var matches=cat.name.match( regex );
                var i=parseInt( matches[0] );
                cat.name=cat.name.replace(i,i+1);
                cat.value='';

                var subcat=clone.querySelectorAll('select[name^="subcategory_"]')[0];
                var matches=subcat.name.match( regex );
                var i=parseInt( matches[0] );
                subcat.name=subcat.name.replace(i,i+1);
                subcat.value='';

                parent.appendChild( clone );
            }

            function bindEvents(){
                var bttn=document.getElementById('addsection');
                    bttn.addEventListener( 'click', clone_section.bind( bttn ), false );
            }
            document.addEventListener('DOMContentLoaded',bindEvents,false);
        </script>
    </head>
    <body>
        <?php
            if( $_SERVER['REQUEST_METHOD']=='POST' && !isset( $_POST['action'] ) ){
                print_r( $_POST );
            }
        ?>
        <form name='geronimo' method='post'>

        <!--// markup from question //-->


        <div id='sform' class='tab-pane fade'>
            <br />
            <div class='col-md-12' id='clone-parent'>

                <!-- it is the following portion of HTML that is to be replicated? -->

                <div class='col-md-10 clone-section'><!-- removed ID, added new class -->
                    <div class='panel-group'>
                        <div class='panel panel-default'>
                            <div class='panel-heading'>Section 1</div><!-- this needs to change progammatically or via CSS-->
                            <div class='panel-body'>
                                <b>Number of Questions: </b>
                                <span class='ctr_num'> <input class='form-control' style='width:50px;' name='q_num_1' size='2' placeholder='#' /></span>
                                <br />
                                <b>Select Category</b>
                                <select class='form-control' style='width: 150px;' name='catdd_1' onchange='change_category( event )'>

                                    <!-- PHP removed for example - replaced with dummy data -->

                                    <option>-Please Select One-
                                    <option value='a'>A
                                    <option value='b'>B
                                    <option value='c'>C
                                    <option value='d'>D
                                    <option value='e'>E
                                </select>
                                <br />
                                <b>Select Subcategory</b>
                                <div class='subcategory'>
                                    <select name='subcategory_1' class='form-control subcategory' style='width: 150px;'>
                                        <option>-Please Select One-</option>
                                    </select>
                                    <br />
                                </div>
                                <p>Select Questions</p>
                                <br />
                                <div class='question'></div><!-- assigned as a class rather than id - can be targeted using querySelectorAll etc -->
                                <br />
                            </div>
                        </div>
                    </div>
                </div>

                <!-- end replicated code -->

            </div>
        </div>
        <hr>
        <div class='col-md-2'><!-- add new section button - uses javascript:onclick -->
            <input type='button' name='addsection' class='btn btn-default' value='Add Section' id='addsection' />
        </div>
        <input type='submit' /><!-- to actually submit the form -->

        <!--// end markup from question //-->

        </form>
    </body>
</html>

关于javascript - 使用 PHP/Javascript 中的按钮动态生成 <div> 部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45049646/

相关文章:

javascript - 将值粘贴到输入区域时,无法捕获值

php - 检测文件已更改并自动更新的简单方法是什么?

jquery - 具有拉伸(stretch)的渐变背景的图像 Angular 上的圆 Angular 边框

jquery - 将数组插入日历引导数组内

javascript - 在Jquery上创建事件,为什么没有返回 "this"?

javascript - 如何将数组数组中相同索引处的元素汇总到一个数组中?

javascript - JSON 渲染为 HTML,仅包含最后一个 <li> 元素

javascript - html代码中的js变量

共享服务器上的 PHP 5.4 旧身份验证,无需编辑 mysql 服务器即可修复

php - 显示诸如Facebook之类的YouTube视频链接的标题和描述