显示隐藏的元素

时间:2017-10-08 08:26:19

标签: jquery onclick this hidden elements

我有一个关于jquery代码的问题,因为我不完全理解它是如何工作的。我想知道javascript是如何知道的,当我点击第一个带有类showMore的ahref时,它只取消隐藏了第一个隐藏元素与类hiddenSpan并且当我点击第二个元素时相同,JS完全取消隐藏第二个隐藏元素。这两个元素都有相同的hiddenSpan类,所以如何识别这些元素?

HTML

(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);

的JavaScript

test_data <- as.data.frame(list(
    V1 = c("-0.2372", "0.5231", "0.039", "1.618", "-1.0774"), 
    V2 = c("0.59", "0.7619", "1.7421", "-0.8037", "0.7327"), 
    V3 = c("0.3196", "0.5639", "-0.289", "-0.0822", "0.176"), 
    V4 = c("-1.2442", "0.2814", "-0.924", "0.9123", "-0.4972"), 
    V5 = c("ST 123E", "LD 34", "ST 123E", "ST 123E", "ST 123E")))

str(test_data)

1 个答案:

答案 0 :(得分: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.
    }

});