Javascript html() 函数后的 jquery 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11826484/
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
jquery event after html() function
提问by Alfonso Fernandez-Ocampo
Is there a way to launch an event after html() has been fired? Such as:
有没有办法在 html() 被触发后启动一个事件?如:
$.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);
});
});
回答by Billy Moon
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.
然而,正如其他人所说,它是不必要的,因为它是.html()
同步的,所以你可以把你的代码放在它后面而不是在回调中。
Demo: http://jsfiddle.net/billymoon/a49P4/
演示:http: //jsfiddle.net/billymoon/a49P4/
回答by Utkanos
html()
is a synchronous operation, not an event, and so it would not logically accept a callback.
html()
是一个同步操作,而不是一个事件,因此它在逻辑上不会接受回调。
Just put your code after it:
只需将您的代码放在它后面:
$('container').html(data);
alert('test');
回答by Purag
This syntax may also be of interest to you:
您可能也对以下语法感兴趣:
$(selector).html(function(index,oldHTML){
alert("test");
return data;
});
回答by Ekim
You can include the javascript code in your html response. An inline example:
您可以在 html 响应中包含 javascript 代码。内联示例:
$("#content").html("hello\<script>\alert('hello');\</script\>");?
would update the div and also execute the code.
将更新 div 并执行代码。
回答by Esailija
No but there is no reason you couldn't do this:
不,但没有理由你不能这样做:
$.post("ajax.php", {data :data}, function(data){
$("#countries").html(data);
var id = $("#countries option:selected").attr("id");
getRegions(id);
});