3

我正在使用 Ajax / Request 将元素加载到 div 容器中。默认情况下,我隐藏了一个输入框。如果用户单击该 div 上的编辑图标,我想显示输入框。这是我的代码:

代码

    <div class='container'>
      <input type = 'text' onkeydown='saveFn(event,this)' name = 'editemail' class = 'editemail' style='display:none;     height:20px;' />
    </div>

JS代码

 $(".container").click(function(){
      console.log($(this).find(".editemail").show()); //Note it works fine If i didn't load any new elements into the div.
 });

将新元素加载到容器中之前的控制台日志输出。

   <input type="text" onkeydown="saveFn(event,this)" name="editemail" class="editemail" style="height: 20px; " value="hyther@zohocorp.com" title="press enter to save">

将元素加载到容器后的控制台日志输出。

<input type="text" onkeydown="saveFn(event,this)" name="editemail" class="editemail" style="height: 20px; display: none; " value="saravanan@zohocorp.com" title="press enter to save">

即使我也尝试从这个元素中删除“样式”属性并添加一个新的样式元素,它仍然不起作用。

4

4 回答 4

11

首先你应该阅读 jQuery Docs FAQ 部分:Why_do_my_events_stop_working_after_an_AJAX_request

使用 on() 将处理程序委托给未来的元素

$(document).on('click', ".container", function(){
/* your code*/
})
于 2012-06-20T20:19:39.277 回答
3

试试这个:

$(document).on('click','.container',function(){

http://api.jquery.com/on/

于 2012-06-20T20:18:23.697 回答
1

试试这个:

$('.container').live('click', function(){
     /* Your Code Here */
});
于 2012-06-20T20:24:42.693 回答
0

问题是click()在 ajax 请求之后绑定丢失了。JQuery您可以使用函数来使其正常工作,但是现在.live()不推荐使用此函数,他们鼓励您使用.on()or .delegate()。就我个人而言,我有大量的 headecks 使用.on()并且.delegate()宁愿使用插件livequery。使用 livequery 插件非常简单:

 $(function(){

    $('#elementId').livequery('click',function(){
       //do something on click
    }) 
 });

欲了解更多信息,请访问: .livequery() .on() .delegate()

于 2012-06-20T20:24:01.227 回答