2013-07-18 85 views
0

由於一些奇怪的原因,我的追加只是添加,但不刪除。追加和刪除不工作,因爲他們應該

下面是HTML:

<div class="insert-links"></div> 
<a href="#" id="button" onclick="return false;"> 
<img src="http://a.dryicons.com/images/icon_sets/blue_extended_icons_set/png/64x64/add.png" "> 
</a> 

和jQuery是以下幾點:

<script type='text/javascript'>//<![CDATA[ 
$(function() { 
    var i = 0; 

    $('#button').click(function() { 
     if (i < 10) { 
      $('.insert-links').append('<p style="display: none;" class="new-link"><input tabindex="1" placeholder="Command eg: give #user# 264" style="width:285px\;margin-top: 12px\;" type="text" name="fname" id="fname"/> <input tabindex="1" placeholder="Price" style="width:45px\;background-color:#f4faff\;" title="Price in points of this item" type="text" name="fname" id="fname"/><a href="#" id="buttonremove" onclick="return false;"><img src="http://c.dryicons.com/images/icon_sets/blue_extended_icons_set/png/128x128/remove.png" style="width: 20px;float: right;margin-top: 19px;margin-right: 19px;"></a></p>'); 
      $('.insert-links').find(".new-link:last").slideDown("slow"); 
      i++; 
     } 
    }); 

    $('#buttonremove').click(function() { 
     if (i > 0) { 
      $('#buttonremove').parent('p').remove(); 
      i--; 
     } 
    }); 
});//]]> 
</script> 

任何人都可以幫我嗎?

回答

2

使用jQuery Event Delegation此:

Fiddle Demo

$('.insert-links').on('click', '#buttonremove', function() { 
    if (i > 0) { 
     $('#buttonremove').parent('p').remove(); 
     i--; 
    } 
}); 
+0

非常感謝,這爲我節省了很多時間!非常感謝。 – Farouqxii

0

的問題是,你要綁定的click事件到「buttonremove」當頁面正在加載,在特定的時刻包含段落所有其他元素尚不存在。你必須做的是在#button的點擊中移動綁定代碼。

+0

這很有道理,非常感謝您的解釋! – Farouqxii

相關問題