gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:08:04 25 4
gpt4 key购买 nike

我这里有一小段代码,它连接到一个名为卡拉 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com