2009-11-12 62 views
0

我使用jQuery创建了一个内联编辑输入['text'] snippet。使用jQuery从附加元素中选择一个类

的HTML将是这样的:

<div id="inline"> 
    <span class="item">Color</span> 
</div> 

我被困在此处(here是我的代码):

$('.item').each(function(){ 
    $(this).click(function(){ 
     $(this).hide(); 
     $(this).parent().append(
      '<form method="post" action="" id="inline_form">'+ 
      '<input type="text" value="'+ $(this).html() +'"> <input type="Submit" value="update" />'+ 
      ' <a href="#" class="cancel">Cancel</a></form>' 
     ); 
    }); 
}); 

我要绑定一个click事件类 '.cancel'我已经在上面添加了,所以当我点击取消时,它将删除表单'#inline_form'并显示'.item'

我试过这个

$('.cancel').each(function(){ 
    $(this).click(function(){ 
     $(this).parent('#inline').find('.item').show(); 
     $(this).parent('#inline_form').remove(); 
    }); 
}); 

但它没有奏效。 如何选择“.cancel”,以便我可以在上面放置点击事件?

回答

0

我修改的代码略有下降,我觉得这有预期的效果:

$('.item').each(function(){ 
     $(this).click(function(){ 
       $(this).hide(); 
       $(this).parent().append(
         '<form method="post" action="" id="inline_form">'+  
         '<input type="text" value="'+ $(this).html() +'"> <input type="Submit" value="update" />'+ 
         ' <a href="#" class="cancel">Cancel</a></form>' 
       ); 

       $('.cancel').each(function(){ 
         $(this).click(function(){ 
         $('#inline').find('.item').show(); 
         $('#inline_form').remove(); 
         }); 
       }); 
     }); 
}); 

这里的关键是,你必须要指定为您创建的链接,同时取消功能,因为在此之前链接不存在。

请记住,使用ID字符串进行parent()调用是多余的,因为您的ID必须是唯一的。只有一个元素应该有一个给定的ID,所以当$('#id')总是可以正常工作时,寻找$(something).parent('#id')毫无意义。 “

+0

”这里的关键点是您必须在创建链接的同时指定取消功能,因为在此之前链接不存在。“ 现在您已经提到了它。多谢。 – mdennisa 2009-11-12 03:51:10