How does jquery's show/hide function work?

为君一笑 提交于 2019-11-29 09:53:35

It stores the old display value in a data attribute called olddisplay and then uses the value of that to restore it when showing the element again. See the implementation here. You can check the implementation of any jQuery method on that site.

In the following code snippets I've annotated the important line with a //LOOK HERE comment.

The important part of the show method:

for (i = 0; i < j; i++) {
    elem = this[i];

    if (elem.style) {
        display = elem.style.display;

        if (display === "" || display === "none") {
            elem.style.display = jQuery._data(elem, "olddisplay") || ""; //LOOK HERE
        }
    }
}

When hiding an element it firstly stores the current display value in a data attribute:

for (var i = 0, j = this.length; i < j; i++) {
    if (this[i].style) {
        var display = jQuery.css(this[i], "display");

        if (display !== "none" && !jQuery._data(this[i], "olddisplay")) {
            jQuery._data(this[i], "olddisplay", display); //LOOK HERE
        }
    }
}

And then simply sets the display property to none. The important part:

for (i = 0; i < j; i++) {
    if (this[i].style) {
        this[i].style.display = "none"; //LOOK HERE
    }
}

Note

The above code is taken from jQuery version 1.6.2 and is obviously subject to change in later versions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!