简体   繁体   中英

Why does the this program not work when I add the submit function inside the add function?

It works until I add the click function inside the add function.

How to make it work such that when add function is called from within the check function the flag is incremented only when the user clicks the submit button and then the control is passed back to check function so the correct final value should be 3.

 var flag = 1; if(flag == 1) { $('p').html("xxx"); check(); } function check() { $('#submit').click(function() { if($("#text").val()=="") { alert("Enter some text"); } else { add(); flag++; alert(flag); } }); } function add() { $('#submit').click(function() { flag++; alert("inside add " + flag); }); } 
 <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <div id="myform"> <p id="title"></p> <input type="text" id="text"> <input type="submit" id="submit"> </div> 

You need to add $( document ).ready(function() { ... });

this seems to work as you aspected:

  $( document ).ready(function() { var flag = 1; if(flag == 1) { $('p').text("xxx"); check(); } function check() { $('#submit').click(function() { if($("#text").val()=="") { alert("Enter some text"); } else { add(); flag++; alert(flag); } }); } function add() { $('#submit').click(function() { flag++; alert("inside add " + flag); } )}; }); 
 <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <div id="myform"> <p id="title"></p> <input type="text" id="text"> <input type="submit" id="submit"> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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