在 JavaScript 中使用 onclick() 时遇到问题

Having issues with onclick() in JavaScript

本文关键字:遇到 问题 onclick JavaScript      更新时间:2023-09-26

我有一个复选框 - 当我选中它时,它会打印出一个下拉列表,但是当我取消选中它时,下拉列表不会消失。在取消选中后的第二次点击(即总共第三次点击)时,整个页面消失;当我只想让下拉列表消失而复选框保留时。

我有下面的代码。

<?php 
include('dbcategory.php');
?>
<script type="text/javascript">

var app = true;

function rFields1(elm){
    if (app == false){
var tra = elm.parentNode.parentNode;
tra.remove();
    }
    app = true;
}
function addFields1(){
    if(app == true){    
    var container = document.getElementById("container1");
    var table = document.createElement("table");
    table.border=1; 
    table.cellspacing=0;     
    table.id ="education";
    table.name = "education[]";     
    container.appendChild(document.createTextNode(""));
    var tr = document.createElement("tr");
    var td1 = document.createElement("td");
    td1.valign = "top";
    var slct = document.createElement("select"); //? how do I fix this up
    slct.id = "institution";
    slct.name = "institution[]";
    //some php code that is generating js code
    <?php
    $sql1a = "SELECT * FROM levels ORDER BY id asc";
    $smt1a = $dbs->prepare($sql1a);
    $smt1a -> execute();
    while($row1a=$smt1a->fetch(PDO::FETCH_ASSOC))
    {
        echo("var opt=document.createElement('"option'");'r'n");
        echo("opt.value='$row1a[level]';'r'n");
        echo("opt.text ='$row1a[level]';'r'n");
        echo("slct.appendChild(opt);");
    }
    ?>
    slct.value='<?php echo $_GET['id2']; ?>';                       //container.add(option);
    container.appendChild(slct);//? how do I fix this up
        //      select1.appendChild(option);
    td1.appendChild(slct);
    tr.appendChild(td1);


    container.appendChild(document.createElement("br"));

    table.appendChild(tr);  
    container.appendChild(table);   
    app = false;
    }
    else {
    colour.onclick=function(){
    rFields1(this);};   
        //  app = true;
    }
    }
</script>
<form id="myform" action="" align="center" method="post" enctype="multipart/form-data">
<div id="div2">
<table border="1" cellspacing="0" style="margin-top:12px width="900"">
<colgroup>
<col span="1">
</colgroup>
<input type="hidden" id="idz" name="idz">

<br><H2 align="center">EDUCATION</H2><br>
<div id="container1">
<table border="1" id="education" name="education[]" cellspacing="0" style="margin-top:12px width="900"">
<colgroup>
<col span="1">
</colgroup>
<input name="colour" id="colour" type="checkbox" onclick="addFields1()" />
<a href="#" type="hidden" id="Remove" name="Remove" onclick="rFields1(this)"></a>

</table>
</div>

</table>

</form>
<br>

复选框默认未选中

选中复选框打印出下拉列表

复选框未选中 - 无更改或影响

第二次选中新取消选中的复选框会导致空白屏幕

首次单击复选框时,它会创建下拉列表。第二次单击将执行以下操作:

colour.onclick=function(){
rFields1(this);};   

我不确定为什么它不会崩溃,因为颜色在任何地方都没有定义,但让我们假设它没有。它只会设置 onclick 函数,但不会执行它。因此,第二次单击不会显示任何更改。第三次单击将删除复选框的父项,这基本上会删除您看到的所有内容。

我想你必须写一些类似的东西

document.getElementById("education").remove();
app = true;

在你的其他情况下,摆脱rFields1。