[英]jQuery: Call a function twice
I'm trying to run a function twice. 我试图两次运行一个函数。 Once when the page loads, and then again on click.
页面加载一次,然后再次单击。 Not sure what I'm doing wrong.
不知道我在做什么错。 Here is my code:
这是我的代码:
$('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();
}
});
The problem is on line 13 where I call the truncate();
问题出在第13行,我在其中调用
truncate();
function a second time. 再次运行。 Any idea why it's not working?
知道为什么它不起作用吗?
Edit jsFiddle here: http://jsfiddle.net/g6PLu/ 在此处编辑 jsFiddle: http : //jsfiddle.net/g6PLu/
That's a named function literal. 那是一个命名函数文字。
The name is only visible within the scope of the function. 该名称仅在功能范围内可见。
Therefore, truncate
doesn't exist outside of the handler. 因此,在处理程序外部不存在
truncate
。
Instead, create a normal function and pass it to each()
: 相反,创建一个普通函数并将其传递给
each()
:
function truncate() { ...}
$('div').each(truncate);
What's the error message do you get? 您得到什么错误信息?
You should create function and then call it as per requirement 您应该创建函数,然后根据需要调用它
Define the function 定义功能
function truncate(){
$('div').each(function(){
});
}
Then call the function 然后调用函数
truncate();
Another approach is to establish, then trigger, a custom event : 另一种方法是建立然后触发自定义事件:
$('div').on('truncate', function() {
$(this).......;
}).trigger('truncate');
Then, wherever else you need the same action, trigger the event again. 然后,在其他需要执行相同操作的地方,再次触发该事件。
To truncate all divs : 截断所有div:
$('div').trigger('truncate');
Similarly you can truncate just one particular div : 同样,您只能截断一个特定的div:
$('div#myDiv').trigger('truncate');
The only prerequisite is that the custom event handler has been attached, so ... 唯一的先决条件是已附加自定义事件处理程序,因此...
$('p').trigger('truncate');
would do nothing because a truncate handler has not been established for p
elements. 不会执行任何操作,因为尚未为
p
元素建立截断处理程序。
I know there's already an accepted answer, but I think the best solution would be a plugin http://jsfiddle.net/g6PLu/13/ It seems to be in the spirit of what the OP wants (to be able to call $('div').truncate
). 我知道已经有一个可以接受的答案,但是我认为最好的解决方案是使用插件http://jsfiddle.net/g6PLu/13/。这似乎符合OP的要求(能够调用
$('div').truncate
)。 And makes for much cleaner code 并使代码更简洁
(function($) {
$.fn.truncate = function() {
this.addClass('closed').children(":not('.truncate')").hide().slice(0,2).show();
};
$.fn.untruncate = function() {
this.removeClass('closed').children().show();
};
})(jQuery);
$('div').truncate();
$('.truncate').click(function() {
var $parent = $(this).parent();
if ($parent.hasClass('closed')) {
$parent.untruncate();
} else {
$parent.truncate();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.