第一位和第二個朋友的代碼有什么區別或者利弊嗎
為什么“夫唯不爭”這位朋友的代碼有時候多點擊幾次“更多”“簡化”就提示出錯了呢~點贊數最多的這個沒有顯示出錯。
代碼如下①
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
<title>挑戰題</title>
</head>
<body>
? ? <ul>
? ? ? ? <li>001</li>
? ? ? ? <li>002</li>
? ? ? ? <li>003</li>
? ? ? ? <li>004</li>
? ? ? ? <li>005</li>
? ? ? ? <li>006</li>
? ? ? ? <li>007</li>
? ? </ul>
? ? <a ?href="javascript:;">更多</a>
? ? <script>
? ? ? ? $(function(){
? ? ? ? ? ? $("li:eq(3)").css("display","none");
? ? ? ? ? ? $("li:eq(4)").css("display","none");
? ? ? ? ? ? $("a").click(function(){
? ? ? ? ? ? ? ? if($("a").text() === "更多"){
? ? ? ? ? ? ? ? ? ? $("a").text("簡化");
? ? ? ? ? ? ? ? ? ? $("li:eq(3)").css("display","list-item");
? ? ? ? ? ? ? ? ? ? $("li:eq(4)").css("display","list-item");
? ? ? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? ? ? $("a").text("更多");
? ? ? ? ? ? ? ? ? ? $("li:eq(3)").css("display","none");
? ? ? ? ? ? ? ? ? ? $("li:eq(4)").css("display","none"); ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? }
? ? ? ? ? ? });
? ? ? ? })
? ? </script>
</body>
</html>
②
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>挑戰題</title>
<style>
? ? .no{display:none;}
</style>
</head>
<body>
? ? <ul>
? ? ? ? <li>11</li>
? ? ? ? <li>22</li>
? ? ? ? <li>33</li>
? ? ? ? <li>44</li>
? ? ? ? <li class="no">55</li>
? ? ? ? <li class="no">66</li>
? ? ? ? <li>77</li>
? ? </ul>
? ? <a href="#" id="aaa">更多</a>
? ? <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
? ? <script>
? ? ? ? $(function(){
? ? ? ? ? ? $("#aaa").click(function(){
? ? ? ? ? ? ? ? var text = $("#aaa").text();
? ? ? ? ? ? ? ? if(text == "更多"){
? ? ? ? ? ? ? ? ? ? $("#aaa").html("簡化");
? ? ? ? ? ? ? ? ? ? $("li[class=no]").show();
? ? ? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? ? ? $("#aaa").html("更多");
? ? ? ? ? ? ? ? ? ? $("li[class=no]").hide();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? });
? ? ? ? });
? ? </script>
</body>
</html>
2016-07-17
我是這樣寫的,“夫唯不爭”這位朋友的代碼我,個人感覺脫離結構和行為分離的想法,所以不推薦使用。而且他假如加更多的li 就逐個在結構上加class ,第一個用eq過濾選擇器也不太推薦,gt選擇器比較好 大于索引值的都隱藏,加多少li都可以簡化四個。隱藏更多。
2016-07-16
if($("a").text() === "更多")這里多了一個“=”號。
if($("a").text() == "更多"){
? ? ? ? ? ? ? ? ? ? $(this).text("簡化");
? ? ? ? ? ? ? ? ? ? $("li:eq(3)").css("display","block");
? ? ? ? ? ? ? ? ? ? $("li:eq(4)").css("display","block");
? ? ? ? ? ? ? ? }
寫法很多差異性,能實現就行。