问题
So as a python guy I am experimenting with JS and Jquery. I wrote this small script to fold \ unfold a menu bar on a html page using Jquery slide. I believe this should work fine, however all it does is freezing my browser for around 10 secs after which in the console I get "script terminated by timeout". Anyone can point me in the right direction?
$(document).ready(function(){
var Clicked = false;
while (true) {
if (Clicked) {
$("button").click(function(){
$("#menu").slideDown();
$("button").replaceWith("<button type=\"button\">↑</button>");
Clicked = false;
});
} else {
$("button").click(function(){
$("#menu").slideUp();
$("button").replaceWith("<button type=\"button\">↓</button>");
Clicked = true;
});
}
}
});
回答1:
The issue is due to the while()
loop. In JS this is a synchronous operation which blocks all other threads (including, importantly, the UI renderer) which causes the browser to hang. This is why you see the alert stating that the operation has been terminated.
A better approach to this is to just have a single event handler which toggles the state of #menu
and the text in the button
which is clicked. Try this:
$(function() {
$("button").click(function() {
$("#menu").slideToggle();
$(this).html(function(i, h) {
return h === '↑' ? '↓' : '↑';
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button">↓</button>
<div id="menu">
Menu...
</div>
回答2:
Your while
loop is infinite. It keeps going to an else
section and attaching onClick
events to the button. I think you can simplify your code by eliminating unnecessary loop, Clicked
variable and using only one onClick
event handler to toggle menu.
I also changed replaceWith
method with jQuery's html() which just takes HTML code as a parameter and puts it inside of your button depending on it's visibility.
$(document).ready(function(){
$("button").click(function(){
$("#menu").slideToggle();
var thisButton = $(this);
if (thisButton.is(':visible')) {
thisButton.html('↑');
} else {
thisButton.html('↓');
}
});
});
来源:https://stackoverflow.com/questions/50275672/javascript-jquery-script-terminated-by-timeout