10

有没有办法在 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);
   });
});
4

5 回答 5

22

是的你可以...

// 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'})

但是,就像其他人所说的那样,.html()同步是不必要的,因此您可以将代码放在它后面而不是回调中。

演示:http: //jsfiddle.net/billymoon/a49P4/

于 2012-08-06T10:43:20.613 回答
2

html()是同步操作,而不是事件,因此它在逻辑上不会接受回调。

只需将您的代码放在它后面:

$('container').html(data);
alert('test');
于 2012-08-06T10:28:59.220 回答
2

您可能也对这种语法感兴趣:

$(selector).html(function(index,oldHTML){
    alert("test");
    return data;
});
于 2012-08-06T10:29:29.227 回答
1

您可以在 html 响应中包含 javascript 代码。内联示例:

  $("#content").html("hello\<script>\alert('hello');\</script\>");​

将更新 div 并执行代码。

于 2012-08-06T10:32:01.493 回答
0

不,但没有理由你不能这样做:

$.post("ajax.php", {data :data}, function(data){
   $("#countries").html(data);
   var id = $("#countries option:selected").attr("id");
   getRegions(id);
});
于 2012-08-06T10:28:42.030 回答