jQuery 如何在jQuery的addClass方法中添加回调函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14567990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a callback function to the addClass method of jQuery?
提问by Mihai Matei
I'm using Prettify from Google and Markdown and I want each time I find a pre
code added in the markdown textarea
to call again the prettyPrint()
function.
我正在使用来自 Google 和 Markdown 的 Prettify,并且每次我在 Markdown 中找到pre
添加的代码时,我都希望textarea
再次调用该prettyPrint()
函数。
This is my actual code:
这是我的实际代码:
if($('#wmd-preview').length > 0) {
$('#wmd-preview').on('DOMNodeInserted DOMNodeRemoved',function(){
$(this).find("pre").not('.prettyprint').addClass("prettyprint");
});
}
But I want something like:
但我想要这样的东西:
$(this).find("pre").not('.prettyprint').addClass("prettyprint",function(){
prettyPrint();
});
Is there any possible way to achieve this?
有没有可能的方法来实现这一目标?
采纳答案by Viktor S.
As far as I understand, you need this:
据我了解,你需要这个:
$(this).find("pre").not('.prettyprint').each(function(){
$(this).addClass("prettyprint");
prettyPrint();
})
回答by A. Wolff
You could extend .addClass()
jquery's method to let it accept a callback function:
您可以扩展.addClass()
jquery 的方法以使其接受回调函数:
;(function ($) {
var oAddClass = $.fn.addClass;
$.fn.addClass = function () {
for (var i in arguments) {
var arg = arguments[i];
if ( !! (arg && arg.constructor && arg.call && arg.apply)) {
setTimeout(arg.bind(this));
delete arguments[i];
}
}
return oAddClass.apply(this, arguments);
}
})(jQuery);
Then use it as usual:
然后像往常一样使用它:
$('pre:not(.prettyprint)').addClass('prettyprint',prettyPrint);
回答by Ionic? Biz?u
The addClass
jQuery function doesn't have a callback in arguments.
在addClass
jQuery的功能并没有在参数的回调。
Read more about this in documentation.
在文档中阅读更多相关信息。
I think that this sould work for you:
我认为这对你有用:
// prettyprint class is added
$(this).find("pre").not('.prettyprint').addClass("prettyprint");
// after prettyprint class is added, prettyPrint function is called
prettyPrint();