生成具有唯一ID或名称或类的特定div?用PHP / Javascript

时间:2017-07-14 05:38:45

标签: javascript php jquery mysql ajax

下面的代码显示了单击按钮添加部分时要生成的div。我想为每个部分唯一地生成它,以便它不会完全复制它,否则它会弄乱数据。

surveycontent.php

<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 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><!-- assigned as a class rather than id - can be targeted using querySelectorAll etc -->
                               <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里面的代码,它太动态了。这是我的代码的完整外观,包括子类别和问题的div id背后的php代码。

surveycontent.php

    <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 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><!-- assigned as a class rather than id - can be targeted using querySelectorAll etc -->
                               <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>

    <br>

<div class="col-md-12">
    <div class=col-md-1><input type="submit" name="submit" id="btnSaveSurvey" class="btn btn-success" value="Submit" /></div>


                <div class=col-md-1><input type="button" class="btn btn-danger" value="Reset Survey" /> </div>
</div>




</body>



</html>




<script type="text/javascript">

    function showUser(str,id) {
        if (str == "") {
            document.getElementById("txtHint").innerHTML = "";
            return;
        } else {
            if (window.XMLHttpRequest) {
                // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            } else {
                // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    /* use id supplied */
                    document.getElementById(id).innerHTML = this.responseText;
                }
            };
            xmlhttp.open("GET","hay.php?q="+str,true);
            xmlhttp.send();
        }
    }

    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;


    }

    //subcat level
    function addQues()
    {
        var c = "insertQuesHere" + (parseInt(document.getElementById("q_num").value) + 1).toString();
        var xmlhttp=new XMLHttpRequest();
        xmlhttp.open("GET","ajax.php?main=0&addQues=yes&subcategory="+document.getElementById("subcategorydd").value+"&cnt="+document.getElementById("q_num").value,false);
        xmlhttp.send(null);
        //alert("insertQuesHere" + document.getElementById("q_num").value .toString());

        document.getElementById(c).innerHTML= xmlhttp.responseText;

        //alert("ajax.php?addQues=yes&subcategory="+document.getElementById("subcategorydd").value+"cnt="+document.getElementById("q_num").value);

        document.getElementById("q_num").value = parseInt(document.getElementById("q_num").value) + 1;

    }
    // category level
    function addQues_Cat()
    {

        var c = "insertQuesHere" + (parseInt(document.getElementById("q_num").value) + 1).toString();
        var xmlhttp=new XMLHttpRequest();
        xmlhttp.open("GET","ajax.php?main=1&addQues=yes&subcategory="+document.getElementById("categorydd").value+"&cnt="+document.getElementById("q_num").value,false);
        xmlhttp.send(null);
        //alert("insertQuesHere" + document.getElementById("q_num").value .toString());

        document.getElementById(c).innerHTML= xmlhttp.responseText;

        //alert("ajax.php?addQues=yes&subcategory="+document.getElementById("subcategorydd").value+"cnt="+document.getElementById("q_num").value);

        document.getElementById("q_num").value = parseInt(document.getElementById("q_num").value) + 1;


    }

    function checkValues()
    {

        var sameValue = false;
        var cnt = parseInt(document.getElementById("q_num").value);

        for (var i = 1; i <= cnt; i++)
        {
            var a = "question_dropdown"+i.toString();
            for (var j = 1; j <= cnt; j++)
            {
                var b = "question_dropdown"+j.toString();
                if(document.getElementById(a).value ==  document.getElementById(b).value && i != j)
                    sameValue = true;
            }
        }

        if(sameValue == true) {
            alert("No duplicate questions allowed.");
            return false;
        }
        else
            return true;
    }

    function delQues()
    {

        var a = "ques"+document.getElementById("q_num").value.toString();
        //alert(a);
        var element = document.getElementById(a);
        element.outerHTML = "";
        delete element;


        document.getElementById("q_num").value = (document.getElementById("q_num").value - 1);

    }


    $(document).ready(function(){
        $("#execute").click(function(){
            var numQ = +$('#q_num').val();
            //Loop--
            for(var ctr=0; ctr < numQ; ctr++){
                var str = load_questions();
                $("#divQuestions").append(str);
            }
        });
    });



</script>

ajax.php(这些div id背后的代码)

<?php
$con = mysqli_connect("localhost","root","","imetrics");

$category= isset($_GET["category"])?$_GET["category"]:"";
$subcat=isset($_GET["subcategory"])?$_GET["subcategory"]:"";
$question=isset($_GET["subcategory"])?$_GET["subcategory"]:"";
$cnt=isset($_GET["cnt"])?$_GET["cnt"]:"";
$addQues=isset($_GET["addQues"])?$_GET["addQues"]:"";
$main=isset($_GET["main"])?$_GET["main"]:"";

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 id='ques{$i}'>
        <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>

    <div id='txtHint{$i}'><b>Person info will be listed here...</b></div>
    <br /></form>";
    }
    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 id='ques{$i}'>
        <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>

    <div id='txtHint{$i}'><b>Person info will be listed here...</b></div>
    </form>  
    <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>";
}


//add ques
if($subcat !="" && $addQues=="yes" && $cnt != "")
{
    $i = 0;
    $num = $cnt + 1;
    //echo $num;
    if($main == 1)
    {

        $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 id='ques{$num}'>
        <b id='labelquestion_dropdown{$num}'>Question #{$num}</b>
        <select id='question_dropdown{$num}'". ($cnt + 1) ." class='form-control' onchange=\"showUser( this.value, 'txtHint{$num}' )\" style='width: 300px;' name='question_dropdowns{$num}'>
        <option selected>Select";
        while($row=mysqli_fetch_array($query))
        {
            echo "<option value='{$row['question_id']}'>" . $row["questiontitle"];

        }
        echo
        "</select>

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

        echo "<div id='insertQuesHere".($cnt + 2)."'></div>";
    }

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

        }
        echo
        "</select>

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

        echo "<div id='insertQuesHere".($cnt + 2)."'></div>";
    }
    //
    //echo "<a href='#add_question' onclick='return addQues();'>Add Question</a>";
}



?>

我想生成这个div,因为整个add section按钮的目的就像我跳过逻辑条件分支的第一步。所以我需要让他们的id或类或名称独一无二?

2 个答案:

答案 0 :(得分:1)

在JavaScript中,我正在使用此方法

var getUniqueId = function () {
    return Math.random().toString(36).substr(2, 10);
};

生成的ids "t0917mk342", "z6teqwb2v7"等示例。

答案 1 :(得分:0)

你文件中的

使用一个会话计数器变量来区分你的div id,就像这样

if(!isset($_SESSION['divcounter'])){
   $_SESSION['divcounter'] = 1;
}

然后在你的add ques函数中使用此会话变量,如下所示

$num = $cnt + $_SESSION['divcounter'];
$_SESSION['divcounter']++;