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:
<div id="read开发者_开发百科root" 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.
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. So your function newField
is overwritten by a reference to the element with the id newField
. Since it is now an HTML element, it is evidently "not a function".
WhatWG spec for this. 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.
精彩评论