javascript - 搜索 div 并设置属性的 jQuery 代码

标签 javascript jquery html css

我正在编写一段代码,在页面加载后寻找具有 css 样式 clear: both 的 div,然后添加 css display: none

这是我的代码示例:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" type="text/javascript"></script>
    <script>
    $(document).load(function () { 
      if( $("div").css('clear').toLowerCase() == 'both') { 
        $(this).css("display", "none"); 
        }); 
      });
    </script>
    <title>Check</title>
  </head>
  <body>
     <div>This is visible</div>
     <div style="text-align: center; font-size: smaller; clear: both;">This is not visible.</div>
  </body>
</html>

出于某种原因,这段代码似乎无法运行...我是 jQuery 的新手。有人可以指出我的错误吗?

最佳答案

您可以使用 css() 方法,如下所示。

$('div').css('display', function () {
    if ($(this).css('clear') == 'both')
        return 'none'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>This is visible</div>
<div style="text-align: center; font-size: smaller; clear: both;">This is not visible.</div>

更新:使用$(document).ready代替$(document).load

关于javascript - 搜索 div 并设置属性的 jQuery 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36680314/

相关文章:

javascript - 我可以使用外部数组来匹配用于内容脚本注入(inject)的 URL 吗?

javascript - 如何从 lodash 导入和使用 _.sortBy

javascript - HTML bootstrap popover 函数

javascript - 在 mousedown-mousemove 上禁用滚动(Jquery/javascript)

Javascript - 饮食偏好的条件格式

html - 当用户在该页面上时,导航栏会亮起

javascript - angularjs 指令不起作用(奇怪的问题)

javascript - 如何创建日期为 ("23.03.2010"的对象)

javascript - 它使用 ASP.NET MVC 和 javascript 在 TreeView 中显示 "undefined"

html - 当页面大小时改变下拉菜单的大小