2014-10-06 75 views
3

這些都是我需要刪除一些輸入字段,但我不能夠去除標籤標記jquery刪除div和以前的標籤?

<label class="prfx-row-title">Unique Selling Proposition </label> 
<div class="prfx-row-content"> 
    <input type="text" name="dynamic_usp[0][text]" placeholder="unique selling proposition " value="testing hello world" /> 
    <span class="remove button">Remove USP</span> 
</div> 

$(".remove").live('click', function() { 
      $(this).parent().remove(); 
      $(this).parent().prev('label.prfx-row-title').remove(); 
     }); 

現在只有DIV被刪除,但不是標籤?

有人嗎?

+3

'live' ...哇...過眼雲煙。 (注意:'live'在幾年前已被棄用,並且至少在一年前被刪除。) – 2014-10-06 17:38:24

+0

@TJCrowder我幾乎每天都會看到'.live()',所以當我訪問它時:)它在1.7中被棄用,並在1.9中被刪除,如果我沒記錯的話。 – Regent 2014-10-06 17:41:19

回答

6

這是因爲當刪除div時,它不再在DOM中,所以標籤不再是兄弟。首先刪除標籤,那麼div

$(".remove").live('click', function() { 
    $(this).parent().prev('label.prfx-row-title').remove(); 
    $(this).parent().remove(); 
}); 

或者更好:

$(".remove").live('click', function() { 
    $(this).parent().prev('label.prfx-row-title').remove() 
    .end().remove(); 
}); 
+0

Tx Karl這麼簡單,但我沒有看到它。你的縫線解決方案看起來像是贏家;) – alex 2014-10-06 17:47:12

+0

這是最簡單的事情,通常很難找到;) – 2014-10-06 17:50:12

4

不能從東西不再有刪除prev() ......所以,最簡單的解決僅僅是重新排列順序...

$(".remove").live('click', function() { 
    $(this).parent().prev('label.prfx-row-title').remove(); 
    $(this).parent().remove(); 
}); 

另外,如果可能的話,你可能要更新您正在使用的jQuery版本,並使用on()而不是live()live()自1.7已被棄用,刪除,因爲1.9

JSFiddle


你也可以考慮改變你的DOM來像...

<div class="prfx-row"> 
    <label class="prfx-row-title">Unique Selling Proposition</label> 
    <div class="prfx-row-content"> 
     <input type="text" name="dynamic_usp[0][text]" placeholder="unique selling proposition " value="testing hello world" /><span class="remove button">Remove USP</span> 

    </div> 
</div> 

和方式,您可以只執行。 。

$(this).closest("prfx-row").remove(); 

JSFiddle

+0

棒極了! tx alreay gav Karl-Andre接受的答案對不起 – alex 2014-10-06 17:46:16

+0

tx @smerny與。 $(本).closest( 「prfx行」)。remove()方法。你的建議也像魅力一樣起作用。 – alex 2014-10-06 17:58:58

+0

@alex是的,我覺得這是一個很好的習慣來包裝這樣的內容。 – smerny 2014-10-06 19:20:12