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
233 views
in Technique[技术] by (71.8m points)

javascript - How to call a function which is inside another function's if statement

I am trying to run this type of code:

Javascript Code:

var a = new XMLHttpRequest();
a.open('GET', 'text.txt');
a.onreadystatechange = function() {
    var a_text = a.responseText;
    If (a_text == "text I have written."){
        document.getElementById("elem").innerHTML= a_text;
        function z() {
            document.getElementById("elem2").setAttribute("class", "invisible");
        };
    } else {
        alert("Sorry, Text doesn't match.");
    };
};
  
function click() {
    z(); 
    //Some other codes 
}

HTML Code:

<!DOCTYPE html>
<html>
    <head>
        <title>Hello</title>
        <style type="text/css" media="all">
            .invisible {
                display: none;
            }
        </style>
    </head>
    <body>
        <p id="elem"></p>
        <p id="elem2">Click the button to make me invisible.</p>
        <button onclick="click()">Click Me</button>
        <script src="javascript.js" type="text/javascript"></script>
    </body>
</html>

At the last I want that when I click on the button, function click() runs and function z() runs only if a_text matches required text. But even if the text matches, the console shows that z() is not defined.

Please include if you have any alternative code to do it easily.

Help me out please.

This is a part of my code where I need the help. Solving this part will let me complete my project.


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

1 Reply

0 votes
by (71.8m points)

z() is not defined.

Because z() declared on inside the ajax callback not as a global.

And also not necessary do like this. You could do with declare as global function. And if you need any special behaviour with in function you could pass with params

Updated

var a_text = '';

function z() {
  if(a_text == "text I have written.") {
    document.getElementById("elem").innerHTML = a_text;
    document.getElementById("elem2").setAttribute("class", "invisible");
  } else {
    alert("Sorry, Text doesn't match.");
  }
};



var a = new XMLHttpRequest();
a.open('GET', 'text.txt');
a.onreadystatechange = function() {
  a_text = a.responseText;
}

function click() {
  z();
  //Some other codes 
}

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

...