[英]Javascript Uncaught Reference error Function is not defined
檢查 Fiddle 以查看發生的故障。
當我將數據(即使我將其留空)添加到文本框並嘗試單擊“添加”時,它不會執行任何操作。
打開 Chrome 和 Firefox 控制台都給我同樣的錯誤,它說“changeText2()”沒有定義。
我怎樣才能解決這個問題? 我已經多次遇到這個錯誤,而且大多數情況下它有非常奇怪的解決方法,但我不確定避免它的方法或我什至做錯了什么。
似乎在大多數情況下刪除全局變量聲明可以修復它,但是,在這種情況下我需要它們並且寧願知道為什么以及如何發生此錯誤。
非常感謝任何和所有幫助。
Javascript:
var list = document.getElementById('deliveryIdArray');
var names = [];
function changeText2() {
var deliveryIdentification = document.getElementById('deliveryIdentification').value;
names.push(deliveryIdentification);//simply add new name to array;
//array changed re-render list
renderList();
}
function renderList(){
while (list.firstChild) {
list.removeChild(list.firstChild);
}
//create each li again
for(var i=0;i<names.length;i++){
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(names[i]));
var removeButton = document.createElement('button');
removeButton.appendChild(document.createTextNode("remove"));
removeButton.setAttribute('onClick','removeName('+i+')');
entry.appendChild(removeButton);
list.appendChild(entry);
}
}
function removeName(nameindex){
names.splice(nameindex,1);
//array changed re-render list
renderList();
}
function getDeliveries(){
return names;
}
HTML:
<b>Number(s): </b>
<input id = "deliveryIdentification" name = "deliveryIdentification" type = "text" size = "16" maxlength = "30">
<!-- Array Area Creation -->
<input type='button' onclick='changeText2()' value='Add' />
<ol id="deliveryIdArray">
</ol>
小提琴: http : //jsfiddle.net/vSHQD/
在 JSFiddle 中,當您將包裝設置為“onLoad”或“onDomready”時,您定義的函數僅在該塊內定義,並且不能被外部事件處理程序訪問。
最簡單的解決方法是更改:
function something(...)
到:
window.something = function(...)
將包裝從“ onload
”更改為“ No wrap - in <body>
”
定義的函數具有不同的作用域。
如果您使用的是 Angular.js,則函數會嵌入到 HTML 中,例如 onclick="function()" 或 onchange="function()"。 他們不會注冊。 您需要在 javascript 中進行更改事件。 如:
$('#exampleBtn').click(function() {
function();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.