1

我从一个包含标题的 div 框开始。

我希望有一个toggle()事件,当单击标题时,它将标题字符串存储到一个变量中,更改该标题的 HTML,并为parent()包含它的 div 框设置动画。

第二个功能是parent()再次为 div 框设置动画,并将 HTML 更改回其原始文本(将存储为变量。)

不过我遇到了麻烦,我不确定我的问题出在哪里。我html()用来“获取”原始标题的字符串,但我不确定这是否正确。我也不确定是否需要更多预防措施来传递变量或正确调用变量。

http://jsfiddle.net/94nPv/1/

请让我知道我做错了什么。非常感谢。

4

1 回答 1

3

可以使用.data()方法存储原始html http://jsfiddle.net/94nPv/3/

jQuery(document).ready(function($) {
    $('h5').toggle(function() {
        var $this = $(this);
        $this.data('originalText',$this.html());
        $this.parent('div.softwarebox').animate({ height: "700px" });
        $this.html("Close");
    }, function() {
        var $this = $(this);
        $this.parent('div.softwarebox').animate({ height: "19px" });
        $this.html($this.data('originalText'));
    });        
});​

略微优化(无需额外调用 .html 或 .data):http: //jsfiddle.net/94nPv/7/

jQuery(document).ready(function($) {
    $('h5').each(function(){
        var $this = $(this);
        $this.data('originalText',$this.html());
    });
    $('h5').click(function() {
        var $this = $(this);
        if ($this.text() === "Close") {
            $this.html($this.data('originalText'));
            $this.parent('div.softwarebox').animate({
                height: "19px"
            });
        }
        else {
            $this.text("Close");
            $this.parent('div.softwarebox').animate({
                height: "700px"
            });
        }
    });
});​
于 2012-06-14T19:44:21.787 回答