[英]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. 直到我将add函数添加到click函数中之前,此方法一直有效。
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. 如何使其工作,以使得当从检查功能中调用添加功能时,仅当用户单击提交按钮时该标志才递增,然后将控件传递回检查功能,因此正确的最终值应为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() { ... });
您需要添加
$( 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.