javascript - 原生组件js在new对象的时候对象被后new的实例替换

查看:147
本文介绍了javascript - 原生组件js在new对象的时候对象被后new的实例替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">
<title>Document</title>
<script src="jquery-1.9.1.min.js"></script>
<style>

  • {padding:0px; margin:0px;}

  1. {list-style:none;}
    #oDiv,#oDiv2 {margin:20px;}
    .hd li {width:60px;height:35px;border:1px solid #000000;float:left; text-align:center; line-height:35px;cursor:pointer;margin-left:-1px;}
    .action {background:red; color:#ffffff;}
    .bg {width:181px;height:200px;border:1px solid #000000;}
    .bg-1 {display:none;}
    </style>
    </head>

<body>

<div id="oDiv">
    <ul class="hd">
        <li class="action">1</li>
        <li>2</li>
        <li>3</li>
    </ul>
    <div class="bg">
        <div class="bg-1" style="display:block;">111</div>
        <div class="bg-1">222</div>
        <div class="bg-1">333</div>
    </div>
</div>
<div id="oDiv2">
    <ul class="hd">
        <li class="action">1</li>
        <li>2</li>
        <li>3</li>
    </ul>
    <div class="bg">
        <div class="bg-1" style="display:block;">1112</div>
        <div class="bg-1">2222</div>
        <div class="bg-1">3333</div>
    </div>
</div>
<script>
  $(function() {
      var obj1 = new Tab();
       obj1.init({id : "#oDiv",events : "click"});
       
      var obj2 = new Tab();
       obj2.init({id : "#oDiv2",events : "click"});
  });
   
   function Tab() {
         this.hd = null;//控制层
         this.bg = null;//被控制对象
         this.num = 0;//当前位置
         this.json = {//默认参数
              events : "click",
              delay : 200
         }
   }
   Tab.prototype.init = function(options) {
          $.extend(this.json,options);
       this.hd = $(options.id).find('.hd li');
       this.bg = $(options.id).find('.bg div');
       this.change();
   };
   Tab.prototype.change = function() {
         _this =this;
      var time = null;
          
       this.hd.on(_this.json.events,function() {
           _this.json.num = $(this).index();

           if(_this.json.events == "mouseover") {
                   
               time = setTimeout(function() {
                  show();
                  
               },_this.json.delay);
           } else {
                 show();
           };
           

       }).on('mouseout',function() {
             clearTimeout(time);
       });

      function show() {

           _this.hd.removeClass('action');
           _this.bg.css('display','none');
           _this.hd.eq(_this.json.num).addClass('action');
           _this.bg.eq(_this.json.num).css('display','block');
      }
      
   }
</script>

</body>
</html>

解决方案


你这里声明的_this是全局的了,后面的实例_this指向变了

这篇关于javascript - 原生组件js在new对象的时候对象被后new的实例替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆