jQuery类似电影院座位选取效果代码实例

吐槽君 分类:实例代码

去影院看过电影的朋友对于座位的选取自然不会陌生。

下面就分享一个简单的代码实例,它实现了模拟效果,代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>前端教程网</title>
<style>
.box > div {
  width: 50px;
  height: 50px;
  background: #ff6700;
  color: #fff;
  margin: 10px;
  float: left;
  cursor: pointer;
  text-align:center;
  line-height:50px;
}
.box > div.on {
  background: #ccc;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script>
$(function () {
  $('.box > div').click(function () {
    $(this).toggleClass('on');
    var str = '';
    $('.box > div').each(function () {
      if ($(this).hasClass('on')) {
        str += $(this).text() + '位,';
      };
    });
    var newstr = str.substring(0, str.length - 1);
    $('.text').text(newstr);
  });
});
</script>
</head>
<body>
已选中的位置有:<span class="text"></span>
<div class="box">
  <div class="i1">011</div>
  <div class="i2">012</div>
  <div class="i1">013</div>
  <div class="i2">014</div>
  <div class="i1">015</div>
  <div class="i2">016</div>
  <div class="i1">017</div>
  <div class="i2">018</div>
  <div class="i1">019</div>
  <div class="i2">020</div>
</div> 
</body>
</html>

上面的代码实现了才选取功能,下面介绍一下它的实现过程。

一.代码注释:

(1).$(function () {}),当文档结构完全加载完毕再去执行函数中的代码。

(2).$('.box > div').click(function () {}),为class属性值为box下的div元素注册click事件处理函数。

(3).$(this).toggleClass('on'),实现当前点击元素class属性值on的添加和删除。

(4).var str = '',声明一个空字符串,后面会用到。

(5).$('.box > div').each(function () {

  if ($(this).hasClass('on')) {

    str += $(this).text() + '位,';

  };

}),遍历每一个div元素。

如果当前div元素具有class属性值on。

那么就将其text文本内容追加到字符串str中。

(6).var newstr = str.substring(0, str.length - 1),作用是去掉最后的逗号。

(7).$('.text').text(newstr),将字符串写入span元素。

二.相关阅读:

(1).toggleClass()可以参阅jQuery toggleClass()一章节。

(2).each()可以参阅jQuery each()一章节。

(3).hasClass()可以参阅jQuery hasClass()一章节。

(4).substring()可以参阅javascript substring()一章节。

jQuery类似电影院座位选取效果代码实例,这样的场景在实际项目中还是用的比较多的,关于jQuery类似电影院座位选取效果代码实例就介绍到这了。

jQuery类似电影院座位选取效果代码实例属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容