简体   繁体   English

以表格形式调用时,Javascript函数“不是函数”

[英]Javascript function 'is not a function' when called in a form

So I have a simple form-extension script: 因此,我有一个简单的表单扩展脚本:

var counter=1;
function newField(counter) {
    counter++;
    var newFields = document.getElementById('readroot').cloneNode(true);
    newFields.id = "formcheck"+counter;
    newFields.style.display = 'block';
    var newField = newFields.childNodes;
    var insertHere = document.getElementById('writeroot');
    insertHere.parentNode.insertBefore(newFields,insertHere);
}

being called inside of a form: 在表单内部被调用:

<form id='newanimal' action='/submit' method='post'>    
<span id='writeroot'></span>
<button id='newField' type='button' onclick=newField();>Add Field</button>
</form>

readroot looks like this: readroot看起来像这样:

<div id="readroot" style="display: none">

<input type="button" value="Remove review"
            onclick="this.parentNode.parentNode.removeChild(this.parentNode); counter--;" /><br /><br />

<input id="checkform" name="checkform" value="New Checkform" />
</div>

Now the function works fine, unless it's called from inside of a form. 现在,该函数可以正常工作,除非从表单内部调用该函数。 When executed as-is, I get newField is not a function called as an error, however if you remove the form tags and it runs fine. 当按原样执行时,我得到的newField is not a function称为错误newField is not a function ,但是,如果删除表单标签,它将正常运行。

Any idea what's going on? 知道发生了什么吗?

<button id='newField' type='button' onclick=newField();>Add Field</button>

When an element has an id property, the element is accessible using the global variable of that name. 当元素具有id属性时,可以使用该名称的全局变量访问该元素。 So your function newField is overwritten by a reference to the element with the id newField . 因此,对id为newField的元素的引用将覆盖newField函数。 Since it is now an HTML element, it is evidently "not a function". 由于它现在是HTML元素,因此显然是“不是函数”。

WhatWG spec for this . 这是WhatWG规范 Note that this is not behaviour you should rely upon, but you should be wary of it for exactly this reason. 请注意,这不是您应该依靠的行为,但正是由于这个原因,您应该对此保持警惕。 Note that unpredictable behaviour in the global scope is a very good reason to avoid using the global scope. 需要注意的是在全球范围内不可预测的行为是一个很好的理由,以避免使用全局范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM