简体   繁体   中英

One of Multiple Scripts in HTML Sheet Not Working

I am trying to have multiple scripts run in my html sheet, and it seems to not be working. All the other scripts work except for the script for the blinking function. I don't see what the problem is. Can you find the issue with my code? Thanks in advance!

Here is my code below:

<!DOCTYPE html>
<html>
<head>
<style>
body {
    background-color: coral;
    color: white;
}

.text2{
  color: white;
  width: 100px;
  float: right;
  padding-top: 10px;
}


</style>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(".btn1").on('click',function(){
     $("p").hide();
     $(".text2").hide()
     $('body').css("background", "black");      
    });

});
</script>

<script>

//blink
var element = $(".text2");
var shown = true;
setInterval(toggle, 500);

function toggle() {
    if(shown) {
        element.hide();
        shown = false;
    } else {
        element.show();
        shown = true;
    }
}
</script>

</head>
<body>

<p>This is a paragraph.</p>

</div>
     <div class="text2">
     -- : --
</div>  
<button class="btn1">online</button>



</body>
</html>

The second script's contents should be in the document ready handler otherwise the code attempts to locate and work with the .text2 element before that element has been parsed into memory.

 <!DOCTYPE html> <html> <head> <style> body { background-color: coral; color: white; } .text2{ color: white; width: 100px; float: right; padding-top: 10px; } </style> <link rel="stylesheet" href="styles.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $(".btn1").on('click',function(){ $("p").hide(); $(".text2").hide() $('body').css("background", "black"); }); var element = $(".text2"); var shown = true; setInterval(toggle, 500); function toggle() { if(shown) { element.hide(); } else { element.show(); } shown = !shown; } }); </script> </head> <body> <p>This is a paragraph.</p> <div class="text2">-- : --</div> <button class="btn1">online</button> </body> </html> 

The second script must be inside a JQuery function.

$(document).ready(function(){
var element = $(".text2");
var shown = true;
setInterval(toggle, 500);

function toggle() {
    if(shown) {
        element.hide();
        shown = false;
    } else {
        element.show();
        shown = true;
    }
}
    });

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