2010-12-10 23 views
0

我正在通过jQuery创建具有焦点和模糊事件的输入元素。由于某些原因,即使显示输入元素,事件也不会触发。这里是一个例子http://jsfiddle.net/9JtLq/8/当通过jQuery动态添加html元素时,事件不会触发(在非IE浏览器中)

这可以在IE7 & IE8。它不适用于Firefox,Safari或Chrome。为什么?

HTML

<div> 
    Try to focus from one input to another. 
</div> 

<div class="placeholder"/> 

<div class="placeholder"/> 

<div id="output" /> 

的javascript:

var input_box = $("<input type=\"text\" />") 
.focus(function() 
{ 
     $("#output").html($("#output").text() + "focus - "); 
}) 
.blur(function() 
{ 
     $("#output").html($("#output").text() + "blur - "); 
}); 


$(".placeholder").append(input_box); 
+3

通过所有的所有当前和未来元素意味着使用jsFiddle和诸如* adjunct *来解决你的问题,但也总是把代码放在*问题中。 SO应该是独立的(外部资源可以消失),并且希望帮助你的人不应该按照链接去做(尽管他们可以选择)。 – 2010-12-10 17:13:25

+0

好点。完成。 – 2010-12-10 17:18:40

回答

1

你应该绑定事件中,你追加后

$(".placeholder").append("<input type=\"text\" />"); 

$(".placeholder input:text").focus(function() { 
    $("#output").html($("#output").text() + "focus - "); 
}).blur(function() { 
    $("#output").html($("#output").text() + "blur - "); 
}); 

http://jsfiddle.net/9JtLq/9/


如果你正在使用jQuery 1.4.1+你可以住绑定模糊和重点,这意味着比赛将被绑定到该事件(一个或多个)

$(".placeholder input:text").live("focus", function() { 
    $("#output").html($("#output").text() + "focus - "); 
}).live("blur", function() { 
    $("#output").html($("#output").text() + "blur - "); 
}); 

http://jsfiddle.net/9JtLq/10/

+0

另外,如果您使用的是不支持'.live'的jQuery版本,则可以使用liveQuery插件:http://plugins.jquery.com/project/livequery – jgradim 2010-12-10 17:18:57

+0

为什么我必须在添加后绑定事件它?此外,我更新了问题,原始代码在IE7和IE8中工作,但不在其他浏览器中。 – 2010-12-10 21:27:33

+0

我假设jQuery不能绑定到不存在的事件,除非你使用'live()'事件。 IE7和IE8可能会有不同的交互。如果你使用live(),你应该很好。 – hunter 2010-12-13 13:59:06

相关问题