Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

html - Javascript Uncaught Reference error Function is not defined

Check the Fiddle to see the failure occurring.

When I add Data (Even if I leave it empty) to the text box and try to click "Add" it doesn't do anything.

Opening the Chrome and Firefox console both give me the same error, it says "changeText2()" is not defined.

How can I fix this? I've ran into this error several times and mostly it had really weird workarounds, but I am not sure as to the method for avoiding it or what I'm even doing wrong.

It seems removing the global variable declarations fixes it most of the time, however, I need them in this case and would rather know why and how this error occurs.

Any and all help is greatly appreciated.

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>

Fiddle: http://jsfiddle.net/vSHQD/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In JSFiddle, when you set the wrapping to "onLoad" or "onDomready", the functions you define are only defined inside that block, and cannot be accessed by outside event handlers.

Easiest fix is to change:

function something(...)

To:

window.something = function(...)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...