此JavaScript代码块做什么?

时间:2018-12-12 18:26:07

标签: javascript jquery

我对JavaScript,jQuery和HTML等非常陌生。我应该在一个项目中实现此代码块(如下),但我不太确定它打算做什么:

$(document).ready(function(){
  $("body").click(function(){
       $(this).hide();
  });
});

我假设它只是隐藏了所有被单击的元素。

5 个答案:

答案 0 :(得分:1)

您是正确的,它隐藏了HTML元素内的所有内容。还要注意,它是使用jQuery编写的,这是一个JavaScript库,该库具有帮助程序功能以使JavaScript更加易于使用。

这里一次一行:

等待页面完成在浏览器中的加载(即DOM或文档对象模型):

$(document).ready(function(){

});

当用户在body元素上触发click事件时,请运行以下功能:

$("body").click(function(){

});

隐藏身体:

$(this).hide();

this (在本文中)指的是上一行中指定的body元素,这与编写相同:`$('body')。hide();

是指根据使用上下文而有所不同的内容。在此示例中,它用于事件中,因此它指的是接收到该事件的元素(正文)。参见W3Schools

.hide()是内置的jQuery函数,可将元素设置为display: none;

答案 1 :(得分:0)

当页面准备好可以执行javascript时,会调用

$(document).ready$("body")选择正文,文档的正文是显示所有可见HTML元素的位置。当点击元素时,将触发click事件。 $(this)选择正在操作的当前元素,即主体。 hide函数隐藏选定的元素,在这种情况下为主体。因此,此代码隐藏了HTML页面的正文,从而导致所有可视元素都被隐藏了。

答案 2 :(得分:0)

很简单,它在body元素上放置了一个“ on click”事件。 也就是说,当您单击body元素时。它将隐藏开头<body>和结尾</body>标签之间的所有内容

<body>
    <!--everything in here will be hidden once body element is clicked-->
</body>

答案 3 :(得分:0)

该代码将使它成为可能,因此单击页面上的任何元素将导致body元素隐藏。

也就是说-除非元素分配了自己的onclick功能,否则使用event.stopPropagation()函数可以阻止事件冒泡到主体元素的onclick。

注意:您还可以在事件处理程序中调用event.stopPropagation(),而不仅仅是将其作为事件处理程序。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
  $(document).ready(function() {
    $("body").click(function() {
      $(this).hide();
    });
  });
</script>
<html>

<head>
  <title>Testing javascript function</title>
</head>

<body>
  <p>Here is one paragraph</p>
  <p>Here is a second paragraph</p>
  <p>Clicking on any element will hide the entire body element.</p>
  <input type="button" value="random button" onclick="event.stopPropagation()" />
</body>

</html>

答案 4 :(得分:0)

这很简单。

示例HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  ...
</body>
</html>

JS:

$(document).ready(function(){ //executes when document model is ready
  $("body").click(function(){ //once u click anywhere on the page this function will be executed
       $(this).hide(); //hides everything between <body></body>
  });
});