2012-09-25 32 views
0

我有一段代碼,當頁面加載時,通過一系列圖像進行檢查並查看其id是否包含單詞video。刪除在jquery中選定圖像周圍的錨標記

如果是這樣,我希望能夠移除圖像周圍的錨定標記。但是,我正在通過.remove()執行此操作的方式將刪除圖像,因爲它位於我要移除的定位標記內。

有沒有辦法只是刪除錨標籤? 注:圖片列表會根據用戶訪問它們拉,所以不會預先確定可以在附加代碼

CODE:

$(document).ready(function() { 
    $('ul.thumbnails li a img').each(function() { 
     if($(this).attr('id').indexOf('video') != -1){ 
      var $parent = $(this).closest('a'); 
      $parent.remove(); 
     } else { 
      $(this).addClass('photo'); 
     } 
    }); 
}); 
+0

也許unwrap()函數 - http://api.jquery.com/unwrap/ – OJay

回答

2

嘗試使用jQuery unwrap

$(document).ready(function() { 
    $('ul.thumbnails li a img').each(function() { 
     if($(this).attr('id').indexOf('video') != -1){ 
      $(this).unwrap(); 
     } else { 
      $(this).addClass('photo'); 
     } 
    }); 
}); 
+0

+1 - 不知道解包! – billyonecan

+0

我也不知道打開包裝!非常感謝。 replaceWith($ parent.contents())也可以,所以感謝這兩個人的貢獻! – MrFirthy

0

問題是你的錨標記包含你的圖像,所以當你刪除你錨定你也刪除它裏面的圖像。試試這個:

$(document).ready(function() { 
    $('ul.thumbnails li a img').each(function() { 
     if($(this).attr('id').indexOf('video') != -1){ 
      var $parent = $(this).closest('a'); 
      $parent.replaceWith($(this).html()); 
     } else { 
      $(this).addClass('photo'); 
     } 
    }); 
}); 

所以我用圖片標籤更換錨標記,而不是刪除錨點

0

當您刪除的元素,所有的孩子也將被刪除。因此,您需要首先克隆並追加圖像。考慮使用克隆功能,尤其是在需要維護事件處理程序時。

嘗試:

$(this).closest('li').append($(this).clone()); 

您刪除$父面前。