×

jQuery is()函数用法3例

作者:Terry2017.02.03来源:Web前端之家浏览:9694评论:0
关键词:JQueryJS

jQuery提供了is()方法可以很方便的判断元素是否可见,是否隐藏,是否选中。

一、判断元素是否隐藏

如下html中的div元素是隐藏的:

复制代码 代码如下:

<!doctype html>
<html>
<head>

<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.7.2.min.js"></script>

</head>
<body>
    <div id="test" style="display:none">你看不到我</div>

<span ></span>
    <script type="text/javascript">
$('span').html('test div is visible? ' + $('#test').is(':visible'));
    </script>
</body>
</html>

二、判断checkbox是否选中

jquery中可以通过xx.is(':checked')判断checkbox,radiobutton是否是选中状态,如下测试html

复制代码 代码如下:

<!doctype html>
<html>
<head>

<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.7.2.min.js"></script>

</head>
<body>
<p>
    <input type="checkbox" name="chkChecked" checked="checked"/> chkChecked
    <input type="checkbox" name="chkNoChecked" /> chkNoChecked
</p>
<span ></span>
    <script type="text/javascript">
$('span').html('chkChecked checked? ' + $('input[name=chkChecked]').is(':checked') + '<br/> '
    +'chkNoChecked checked? ' + $('input[name=chkNoChecked]').is(':checked') );
    </script>
</body>
</html>

三、判断是否使用了某个样式

复制代码 代码如下:

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>is函数介绍</title>
  <style>  //设置一些基本样式
  div { width:60px; height:60px; margin:5px; float:left;
      border:4px outset; background:green; text-align:center;
      font-weight:bolder; cursor:pointer; }
  .blue { background:blue; }  //样式1
  .red { background:red; }//样式2
  span { color:white; font-size:16px; }
  p { color:red; font-weight:bolder; background:yellow;
      margin:3px; clear:left; display:none; }
  </style>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script> //注意 这里使用的是jQuery官方的脚步库
</head>
<body>
  <div></div>  //注意这里出现了第一个div
<div class="blue"></div>//注意这里出现了第2个div
<div></div>//注意这里出现了第3个div
<div class="red"></div>//注意这里出现了第4个div

<div><br/><span>Peter</span></div>//注意这里出现了第5个div
<div class="blue"></div>//注意这里出现了第6个div
<p> </p>
<script>
  $("div").one('click', function () {   //$("div").one  代表对div元素附加一个事件,
//还能附加多个事件 譬如click或者mouseout时同时执行一些事情
    if ($(this).is(":first-child")) { //is函数发挥作用了,is(":first-child") 代表
   //判断此div是否第一个出现的div
      $("p").text("It's the first div."); //text和html区别在于是否支持html标记
  // 此时你在里面写个 alert是不会执行的
    } else if ($(this).is(".blue,.red")) {  //判断该div是否 具有blue或者red的 class
      $("p").text("这是个蓝色或者红色的div");
    } else if ($(this).is(":contains('Peter')")) { //判断div中是否存在Peter这个词
      $("p").text("It's Peter!");
    } else {
      $("p").html("It's nothing <em>special</em>.");
    }
    $("p").hide().slideDown("slow"); //这是一个动画效果。慢慢展现p的内容
    $(this).css({"border-style": "inset", cursor:"default"});
  });
</script>

</body>
</html>

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/svg1486051200673.html

网友评论文明上网理性发言已有0人参与

发表评论: