2014-01-20 43 views
1

我從這裏得到了這個代碼在網站上,它工作得很好jsfidle(http://jsfiddle.net/jaredwilli/tZPg4/4/),但當我把它放在我的網站上時,「刪除」鏈接不會做任何事情,當我點擊它。JS功能刪除元素不起作用

注意:我已將「live」替換爲「on」。

代碼:

HTML:

<h2><a href="#" id="addScnt">Add Another Input Box</a></h2> 

<div id="p_scents"> 
    <p> 
     <label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" /></label> 
    </p> 
</div> 

JS:

$(function() { 
     var scntDiv = $('#p_scents'); 
     var i = $('#p_scents p').size() + 1; 

     $('#addScnt').live('click', function() { 
       $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv); 
       i++; 
       return false; 
     }); 

     $('#remScnt').live('click', function() { 
       if(i > 2) { 
         $(this).parents('p').remove(); 
         i--; 
       } 
       return false; 
     }); 
}); 
+0

你給一個鏈接到其工作的的jsfiddle,你發佈的代碼是完全一樣的,意味着它爲好。我們應該如何幫助你?嘗試重現你在小提琴中所做的事情並更新你的問題。 –

+1

您使用的是哪個版本的jQuery? – dcodesmith

+0

@dcodesmith jquery-2.0.3 – Bob

回答

0

第一個變化是remScntclass,因爲它會在DOM存在超過曾經,

只需嘗試以下,

$(document).on('click','.remScnt', function() { 
    if(i > 2) { 
     $(this).parents('p').remove(); 
     i--; 
     } 
    return false; 
}); 
+0

完成!感謝您的快速建議!它的工作原理= D – Bob

+0

@ user3214754很高興提供幫助。如果您願意,可以將其視爲可接受的答案。 –

+0

我認爲這意味着點擊綠色的複選標記吧?如果是這樣,高興地。 – Bob