javascript - 动态创建的选择框不接受功能添加的选项

标签 javascript php html mysql

我这里有一小段代码,它连接到一个名为卡拉 OK 的数据库并填充一个选择框。我只是希望能够在索引 0 处添加一个选择框选项,上面写着“请选择”之类的内容。我尝试了多种方法在 PHP、HTML 和 Javascript 中执行此操作,但尚未找到我需要的解决方案。到目前为止,这段代码在 Chrome 调试器中显示 0 个错误,但并没有按照我的预期运行。有人可以告诉我我做错了什么吗?

 <!DOCTYPE HTML>
 <html>
  <head>
  <title>Add Singer</title>
  </head>
  <body>
  <center><label style = "color: white; font-family:arial; font-size: 24px">Select a Regular</label></center>

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

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
  $sql = "Select * FROM regulars ORDER BY Regulars ASC";
  $result = mysqli_query($con, $sql) or die("Bad SQL: $sql");
  $opt = "<select id = 'regulars' name = 'regulars'>";
  while($row = mysqli_fetch_assoc($result)) {
      $opt .= "<option value'{$row['Regulars']}'>{$row['Regulars']}</option>\n";
  }
 $opt .="</select>"
?>

<center> <div id="regulars">
<?php
echo $opt;
?>
</div> </center>

<script>
function myFunction() {
    var x = document.getElementById("regulars");
    var option = document.createElement("option");
    option.text = "Please Select";
    x.add(option, x[0]);
}
</sript>
myFunction()
  </body>
</html>

最佳答案

您有一个 id="regulars"的 div 标签。该标 checkout 现在打印出包含 select 元素的 $opt 变量之前,该变量也具有 id="regulars"。 Javascript 代码正在查找第一个具有“regulars”id 的元素,即 div。尝试更改 div 的 id。

正如评论中提到的,myFunction函数调用应该在script标签中。 option 标签应包含 =value 属性。

 <!DOCTYPE HTML>
 <html>
  <head>
  <title>Add Singer</title>
  </head>
  <body>
  <center><label style = "color: white; font-family:arial; font-size: 24px">Select a Regular</label></center>

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

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
  $sql = "Select * FROM regulars ORDER BY Regulars ASC";
  $result = mysqli_query($con, $sql) or die("Bad SQL: $sql");
  $opt = "<select id = 'regulars' name = 'regulars'>";
  while($row = mysqli_fetch_assoc($result)) {
      $opt .= "<option value='{$row['Regulars']}'>{$row['Regulars']}</option>\n";
  }
 $opt .="</select>"
?>

<center> <div id="regularsDiv">
<?php
echo $opt;
?>
</div> </center>

<script>
function myFunction() {
    var x = document.getElementById("regulars");
    var option = document.createElement("option");
    option.text = "Please Select";
    x.add(option, x[0]);
}
myFunction();
</script>
  </body>
</html>

关于javascript - 动态创建的选择框不接受功能添加的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51519238/

相关文章:

php - mysql更新php后空值

javascript - 这个 JSON 有什么问题?

javascript - 在 Symfony2 中使用 jQuery 数据表 |学说| Twig 项目 - 混合一些功能以使选择的标签过滤器在数据表中显示结果

PHP 向多维数组的每个子数组添加元素

php - 基于 PHP 变量的 CSS 媒体查询

PHP - 从基于值名称组合类似值的 php 数组构建多级 HTML 菜单

css - 如何确保文本位于圆 Angular div 内?

javascript - Ajax 文件上传不适用于 IE8

javascript - 参数更改时的 Angular 指令刷新

javascript - Angular JS 将 html 发送到数据库