jquery事件之后html()函数 [英] jquery event after html() function
本文介绍了jquery事件之后html()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在html()被触发后启动一个事件?例如:
$。post(ajax.php,{data:data},function(data){
$(#countries)。html(data,function(){
alert(test);
});
});
这不工作。
编辑:我问这个是因为我想要从调用的信息中做一些事情(另一个调用)...我想简化示例...我猜程序员总是想知道为什么...
所以这里是更新的例子
$ .post(ajax.php ,{data:data},function(data){
$(#countries)。html(data,function(){
var id = $(#countries option:selected .attr(id);
getRegions(id);
});
});
解决方案
是的,你可以...
//创建对旧的`.html()'函数的引用
但是,像其他人一样,不需要
var htmlOriginal = $ .fn.html;
//重新定义`.html()`函数以接受回调
$ .fn.html = function(html,callback){
//运行旧的` .html()`函数与第一个参数
var ret = htmlOriginal.apply(this,arguments);
//运行回调(如果被定义)
if(typeof callback ==function){
callback();
}
//确保链接不被破坏
return ret;
}
//测试它都按预期工作(包括链接)
$(#mything)。html(< div> My Thing< / div> ,function(){
console.log(Just did my thing);
})。css({color:'red'})
.html()
是同步的,所以你可以把你的代码放在后面,而不是回调。
演示: http://jsfiddle.net/billymoon/a49P4/
Is there a way to launch an event after html() has been fired? Such as:
$.post("ajax.php", {data :data}, function(data){ $("#countries").html(data, function(){ alert("test"); }); });
This is not working.
EDIT: I am asking this because I want to do few things(another call) with the information coming from the call... I wanted to simplify the example...I guess programmers always want to know why...
So here it is the example updated
$.post("ajax.php", {data :data}, function(data){ $("#countries").html(data, function(){ var id = $("#countries option:selected").attr("id"); getRegions(id); }); });
解决方案Yes you can...
// create a reference to the old `.html()` function var htmlOriginal = $.fn.html; // redefine the `.html()` function to accept a callback $.fn.html = function(html,callback){ // run the old `.html()` function with the first parameter var ret = htmlOriginal.apply(this, arguments); // run the callback (if it is defined) if(typeof callback == "function"){ callback(); } // make sure chaining is not broken return ret; } // test it all works as expected (including chaining) $("#mything").html("<div>My Thing</div>",function(){ console.log("Just did my thing"); }).css({color: 'red'})
However, like everyone else says, it is unnecessary as
.html()
is synchronous, so you can just put your code following it rather than in a callback.Demo: http://jsfiddle.net/billymoon/a49P4/
这篇关于jquery事件之后html()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文