2017-10-08 209 views
1

我有一個關於jquery代碼的問題,因爲我沒有完全理解它是如何工作的。我想知道javascript是如何知道,當我點擊第一個類showMore時,它只隱藏第一個隱藏的類與hiddenSpan類似,當我點擊第二個元素時,JS隱藏了第二個隱藏的元素。這兩個元素都有相同的hiddenSpan類,因此這些元素如何被識別?顯示隱藏的元素

HTML

<!DOCTYPE html> 
<html> 
<head> 
<title></title> 
<link rel="stylesheet" type="text/css" href="style.css"> 
<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> 
</script> 
</head> 
<body> 
<div class="container flex our-people clearfix"> 
<div class="tile"> 
    <h4>Peter Bolton - Partner</h4> 
    <img src="img.jpg" /> 
    <p>Peter Bolton lives in Burnley with his wife and two children.<span class="hiddenSpan">Peter was admitted as a solicitor in May 1975, having completed two years Articles with a Blackburn firm of solicitors.</span><a href="#" class="showMore">Show more</a></p> 
    <a href="mailto:" class="btn">Send email <i class="fa fa-caret-right" aria-hidden="true"></i></a> 
</div> 
<div class="tile"> 
    <h4>Peter Bolton - Partner</h4> 
    <img src="img.jpg" /> 
    <p>Peter Bolton lives in Burnley with his wife and two children.<span class="hiddenSpan">Peter was admitted as a solicitor in May 1975, having completed two years Articles with a Blackburn firm of solicitors.</span><a href="#" class="showMore">Show more</a></p> 
    <a href="mailto:" class="btn">Send email <i class="fa fa-caret-right" aria-hidden="true"></i></a> 
</div> 
</div> 
<script src="script.js"> </script> 
</body> 
</html> 

的JavaScript

(function($) { 

$(".hiddenSpan").hide(); 

$(document).ready(function() { 

    $(".showMore").on("click", function(e) { 

     e.preventDefault(); 

     var $this = $(this), 
      content = $this.prev(); 

     if(content.is(":hidden")) { 
      content.slideDown(700); 
      $this.text("Show less"); 
     } else { 
      content.slideUp(); 
      $this.text("Show more"); 
     } 

    }); 
}); 

})(jQuery); 
+0

$(本)referances的點擊相冊更多>>暫類。那麼它會針對點擊過的課程的上一次跨度。 –

回答

1
$(".showMore").on("click", function(e) {//this is clicking the class 

    e.preventDefault(); 

    var $this = $(this),//as there is more than one with same class 'this' is referancing the clicke done 
     content = $this.prev();//here he gets the previous element of the clicked one 

    if(content.is(":hidden")) {//asks if it is hidden or no 
     content.slideDown(700);//if hjidden then show it 
     $this.text("Show less");//set the text of a tag to "show less" 
    } else { 
     content.slideUp();// else if not hidden then hide it 
     $this.text("Show more");//the the text of a tag to show more. 
    } 

}); 
+0

非常感謝你:) –

+0

希望它有幫助=)n.p –