appendChild在函数外部工作,但在函数内部不工作

appendChild works outside the function but not inside

本文关键字:函数 工作 内部 外部 appendChild      更新时间:2023-09-26

我的代码的某些部分有问题。我尝试使用JavaScript创建"DIV"answers"P"标记,但只有当我将代码放在函数之外(函数称为"fo")时,它才起作用。当你单击按钮时,会出现一个对话框,如果你单击取消,appendChild方法应该将"DIV"answers"P"标记放在"body"中。

我应该补充一点,p标签中的文本可以在屏幕上短暂地看到,然后突然消失了。我的浏览器是谷歌浏览器。

<html>
<body>
</body>
<script> 
function give(){
form = document.createElement("FORM");
input = document.createElement("INPUT");
input.setAttribute("type", "submit");
input.setAttribute("value", "button");
form.setAttribute("id", "abc");
form.setAttribute("onsubmit", "fo()");
textarea = document.createElement("TEXTAREA");
textarea.setAttribute("id", "txt");
form.appendChild(input);
form.appendChild(textarea);
document.body.appendChild(form);
document.getElementById("abc").method = "post";
}
  give();
  function fo(){
a = document.getElementById("txt").value; 
cfm = confirm("Are you sure you want changes");
if (cfm == false ) {
div = document.createElement("DIV");
p = document.createElement("P");
ptxt = document.createTextNode("test");
p.setAttribute("id", "centr");
p.appendChild(ptxt);
div.appendChild(p);
document.body.appendChild(div);
}
}
/*When this part of code is outside function fo() , appendChild works correctly
  div = document.createElement("DIV");
  p = document.createElement("P");
  ptxt = document.createTextNode("Outside the function it works");
  p.setAttribute("id", "centr");
  p.appendChild(ptxt);
  div.appendChild(p);
  document.body.appendChild(div); 
  */
  </script>
  </html>

您面临表单提交的默认行为,即导航到action属性中指定的页面,或者如果未指定action则重新加载当前页面。

您需要对代码进行以下更改来修复此问题:

  1. 将提交处理程序注册修改为form.setAttribute("onsubmit", "fo(event)");
  2. fo()函数签名更改为fo(event)
  3. 调用if (cfm == false)条件体末尾的event.preventDefault()

所以你的代码看起来是这样的:

<html>
<body>
</body>
<script>
    function give(){
        form = document.createElement("FORM");
        input = document.createElement("INPUT");
        input.setAttribute("type", "submit");
        input.setAttribute("value", "button");
        form.setAttribute("id", "abc");
        form.setAttribute("onsubmit", "fo(event)");
        textarea = document.createElement("TEXTAREA");
        textarea.setAttribute("id", "txt");
        form.appendChild(input);
        form.appendChild(textarea);
        document.body.appendChild(form);
        document.getElementById("abc").method = "post";
    }
    give();
    function fo(event){
        a = document.getElementById("txt").value;
        cfm = confirm("Are you sure you want changes");
        if (cfm == false ) {
            div = document.createElement("DIV");
            p = document.createElement("P");
            ptxt = document.createTextNode("test");
            p.setAttribute("id", "centr");
            p.appendChild(ptxt);
            div.appendChild(p);
            document.body.appendChild(div);
            event.preventDefault();
        }
    }
</script>
</html>