显示隐藏的元素
问题描述:
我有一个关于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);
答
$(".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 –
$(本)referances的点击相册更多>>暂类。那么它会针对点击过的课程的上一次跨度。 –