2009-11-12 50 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

相關問題