所以我试图把它弄清楚几个小时!我正在尝试创建一个通用功能,如果内容只有一定的高度,如果用户点击“显示更多”,它将通过将高度设置为auto来显示整个内容。问题是我使用的是.toggle()
,它需要两个不同的功能。我想以某种方式存储高度的原始值,将其高度更改为自动,然后在用户单击显示/隐藏时恢复其原始高度。页面中会有不同的div,因此需要确保当用户点击显示/隐藏时,它将引用最近的div。
我尝试使用.data()
在两个单独的函数中传递相同的信息,不知怎的,它确实在我第一次执行时工作,但我不知道发生了什么,.data
中存储的值可以不能通过其他功能。
以下是代码:
// When the user clicks the button with the class .more
$('.more').toggle(
//This stores the height of the original div and then sets it height to auto
function (e) {
e.preventDefault();
// This will travel up to the parent and find the corrresponding content div and store its height in a variable oh(original height)
var oh = $(this).parents('.parent')
.find('.content').height();
// im trying to get this information to be pass along the other function
$(this).data('original_height', oh);
$(this).$(this).parents('.parent')
.find('.content')
.css('height', 'auto');
$(this).text('hide');
},
// This function restores the original height of the div
function (e) {
e.preventDefault();
// im trying to get the value of the original_height to be pass along into this function. Howw!!!!
var original_height_value = $(this).data('original_height')
$(this).parents('.' + parent)
.find('.' + content)
.css('height', original_height_value + 'px');
$(this).text('more');
}
});
答案 0 :(得分:0)
代码的data()
部分对我来说似乎很好。我不明白的是这两行:
$(this).$(this).parents('.parent').find('.content').css('height','auto');
和
$(this).parents('.'+ parent).find('.' + content).css('height', original_height_value + 'px');
变量parent
和content
中的内容是什么?
这两行不应该是同一个东西吗?
另外,我不知道为什么你会使用$(this).$(this)
,$(this)
应该没问题。
答案 1 :(得分:0)
Toggle不接受两个函数,只接受一个回调函数: api.jquery.com/toggle
看到你对Hogan的评论:
在第一个函数中,oh
具有正确的值?