我正在尝试运行一个函数两次。页面加载时一次,然后单击时再次。不确定我做错了什么。这是我的代码:
$('div').each(function truncate() {
$(this).addClass('closed').children().slice(0,2).show().find('.truncate').show();
});
$('.truncate').click(function() {
if ($(this).parent().hasClass('closed')) {
$(this).parent().removeClass('closed').addClass('open').children().show();
}
else if ($(this).parent().hasClass('open')) {
$(this).parent().removeClass('open').addClass('closed');
$('div').truncate();
$(this).show();
}
});
问题出在第 13 行,我再次调用 truncate();
函数。知道为什么它不起作用吗?
编辑 jsFiddle:http://jsfiddle.net/g6PLu/
最佳答案
这是一个命名函数文字。
名称仅在函数范围内可见。
因此,truncate
不存在于处理程序之外。
相反,创建一个普通函数并将其传递给 each()
:
function truncate() { ...}
$('div').each(truncate);
关于javascript - jQuery:调用一个函数两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10660066/