单击按钮添加新的<select>标记

时间:2015-12-26 11:42:46

标签: javascript php jquery

我有一个“添加语句”按钮,我需要一个&lt; select&gt;每次单击按钮后都会在我的页面上显示标记(不刷新页面)。这是Select的代码: &lt; select id =“statement”name =“statement”&gt; &LT; PHP    $ select =“SELECT name FROM Statements”;    $ res = $ conn-&gt; query($ select);    while($ row = $ res-&gt; fetch_assoc()){        echo“&lt; option value = \”“。$ row ['name']。”\“&gt;” 。 $ row ['name']。 “&LT; /选项&gt;” 中;    } ?&GT; &LT; /选择&GT; 我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:0)

使用ELEMENT.cloneNode(true)克隆元素,true也克隆子节点:

&#13;
&#13;
var selectionCounter = 0
function cloneSelect() {
  var select = document.getElementById("statement")
  var clone = select.cloneNode(true)
  var name = select.getAttribute("name") + selectionCounter++
  clone.id = name
  clone.setAttribute("name", name)
  document.getElementById("selectContainer").appendChild(clone)
}
&#13;
<div id="selectContainer">
  <select id="statement" name="statement">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
  </select>
</div>

<button onclick="cloneSelect()">Add another Select</button>
&#13;
&#13;
&#13;

此处有关node.cloneNode(deep)的更多信息:https://developer.mozilla.org/en/docs/Web/API/Node/cloneNode

答案 1 :(得分:-1)

我认为它会对你有帮助 -

<script>
   function addOption(){
   var sel = document.getElementById("statement");
   var option = document.createElement("option");
   option.innerHTML = "name";
   option.value = "1";
   sel.appendChild(option);
}
</script>

答案 2 :(得分:-1)

试试这个。它可能会帮助你。

<!DOCTYPE html>
<html>
<head></head>

<body>
<div id="container"></div>
<button type="button" id="add" onclick="addOption()">Add a statement</button>

<?php

$que = mysql_query("SELECT name FROM Statements") or die(mysql_error());

$script = "<script>function addOption(){";
$script .= "var container = document.getElementById('container');";
$script .= "var select = document.createElement('select');";
while($data = mysql_fetch_array($que)){
$script .= "var option = document.createElement('option');";
  $script .= "option.innerHTML = '$data[0]';";
  $script .= "select.appendChild(option);";
}
$script .= "container.appendChild(select);";
$script .= "}</script>";
echo $script;
?>



</body>

</html>