jquery写的选项卡改写成面向对象程序(有赞赏哦)

请教大神,下面这个用jquery写的简单的选项卡,我将它改写成面向对象程序,但是不执行,我感觉可能是this的用法有错,可是不知道错在那里?我是初级小白。

非常感谢,会有赞赏给被采用评论者!

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

<meta charset="UTF-8">

<script src="https://ajax.googleapis.com/a...;></script>
<title>Title</title>
<style>

#tab li {height:50px;width:100px;float:left;background-color:gray;}
#content li{height:200px;width:300px;background-color: deepskyblue;display: none;}
#content li:first-of-type{display:block;}
#tab .current {background-color: yellowgreen;}

</style>
</head>
<body>
<ul id="tab">

<li class="current">tab1</li>
<li>tab2</li>
<li>tab3</li>
</ul >
<ul id="content">
<li >content1</li>
<li>content2</li>
<li>content3</li>
</ul>
<script>
$(document).ready(function(){

$("#tab li").click(function(){

var i=$(this).index();
$("#tab li").removeClass("current");
$(this).addClass("current");
$("#content li").css("display","none");
$("#content li").eq(i).show();

})

})

</script>
</body>
</html>
我的面向对象写法:
$(document).ready(function(){

function Tab (element,showelement) {

$(this).element = element
$(this).showelement = showelement

}

Tab.prototype.showcontent=function(){

$(this).element.click(function(){

 var $This = $(this)
 var i=$This.index()
 $(this).element.removeClass("current")
 $This.addClass("current")
 $(this).showelement.css("display","none")
 $(this).showelement.eq(i).show()

})
}

var a= new Tab($("#tab li"),$("content li"));
a.showcontent();

阅读 1.8k
1 个回答

按照原来的布局和样式,面向对象的写法如下:

$(function(){
    function Tab(ele, showele) {
        // 将当前this的指向赋值给$this变量
        const $this = this

        this.ele = ele
        this.showele = showele
        this.ele.click(function() {
            // 调用原型上的fnClick方法,并将当前被点击的元素作为参数传递
            $this.fnClick($(this));
        })
    }

    Tab.prototype.fnClick = function(cur) {
        const $index = cur.index()

        this.ele.removeClass("current")
        cur.addClass("current")
        this.showele.css("display", "none")
        this.showele.eq($index).show()
    }

    const example = new Tab($("#tab li"), $("#content li"));
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题