JQuery setTimeout to pass error reporting for string parameters
- 2020-03-30 03:19:51
- OfStack
When you want to call some jQuery code to show a hidden element and call setTimeout() to set its HTML content after a delay:
The code for the entire page looks like this.
The.show() call did succeed, but the.text() call failed.
I really don't have a better answer to this question... I wonder if jQuery made a change to the contents of this passed setTimeout() function that invalidated the variable.
I followed up with the next experiment.
I'm going to see if jQuery is really the problem. I'm going to get the same error.
Then I found a book to read and found the problem.
When setTimeout() takes a string parameter, it executes globally, that is, outside of any function.
Solve the problem successfully.
The code for the entire page looks like this.
<span style="font-size:18px;"><html>
<head>
<title></title>
</head>
<body>
<a href="#" id='heihei' onclick="showNext('I am veinei ')">show next</a>
<a href="#" id="log" style="display:none" >yes,I am the next </a>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript">
function showNext(text){
setTimeout("$('#log').show().text(text)",1000);
}
</script>
</body>
</html>
</span>
The.show() call did succeed, but the.text() call failed.
I really don't have a better answer to this question... I wonder if jQuery made a change to the contents of this passed setTimeout() function that invalidated the variable.
I followed up with the next experiment.
<span style="font-size:18px;"><html>
<head>
<title></title>
</head>
<body>
<a href="#" id='heihei' onclick="showNext('I am veinei ')">show next</a>
<a href="#" id="log" style="display:none" >yes,I am the next </a>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript">
function showNext(text){
setTimeout("alert(text)",1000);
}
</script>
</body>
</html>
</span>
I'm going to see if jQuery is really the problem. I'm going to get the same error.
Then I found a book to read and found the problem.
When setTimeout() takes a string parameter, it executes globally, that is, outside of any function.
<span style="font-size:18px;"><html>
<head>
<title></title>
</head>
<body>
<a href="#" id='heihei' onclick="showNext('I am veinei ')">show next</a>
<a href="#" id="log" style="display:none" >yes,I am the next </a>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript">
function showNext(text){
setTimeout(function(){$('#log').show().text(text);},1000);
}
</script>
</body>
</html>
</span>
Solve the problem successfully.