简体   繁体   English

HTML工作表中的多个脚本之一不起作用

[英]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. 我试图在我的HTML表格中运行多个脚本,但似乎无法正常工作。 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. 第二个脚本的内容应位于文档就绪处理程序中,否则代码将尝试在将.text2元素解析到内存之前定位并使用该元素。

 <!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. 第二个脚本必须在JQuery函数内。

$(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;
    }
}
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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