2012-11-15 84 views
0

我如何使用JavaScript的香草+正則表達式來刪除圖像元素,根據它們的來源嗎?刪除圖像元素基於源

我讀了網絡應用程序中的RSS提要。如果源代碼中包含單詞「comments」,我想刪除某些圖片元素。

之前它呈現到頁面上(從HTTP請求剛拔掉,並仍處於「字符串」),這將是理想的編輯RSS提要。

更新: 感謝您的答覆。在每篇文章的最底部,他們都包含了一個評論鏈接......這是我想要刪除的內容。 這裏是在每個製品的最末尾的代碼:

<a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ADDRESS/FEED"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/[ADDRESS]/[FEED]" /></a>

也時,[飼料]值每篇文章的變化。那麼最好是檢查單詞'comments'還是檢查源代碼是否以x開頭?

+0

XML解析器可能會比正則表達式和更好地工作表演肯定會更好。但是,如果您想使用RegEx,請發佈RSS源的小樣本,然後寫一個。 – evanmcdonnal

+0

你是什麼意思他們的源代碼包含單詞「評論」?什麼部分來源?我會假設一個屬性,那麼哪一個?而且不需要正則表達式來做到這一點。 –

+1

@ user1689607'

回答

2
var images = document.getElementsByTagName('img'); 
for (var i = 0; i < images.length; i++) { 
    var img = images[i]; 
    if (img.src.indexOf('comments') > 0) { 
     var link = img.parentNode; 
     link.parentNode.removeChild(link); 
    } 
} 
  • 線1:獲取頁面
  • 線2上的所有圖像元素的列表:遍歷目錄,刪除那些誰的SRC有詞「評論」。這是通過調用任何字符串對象的indexOf方法完成的。 Detailed here
+0

updated: I made a small mistake in the previous answer. now fixed. – lins05

+0

Note: this will remove the _image_. The question currently seems to ask how to remove its _parent_. –

+0

Hi. Thanks for your reply. You're code needed a bit of tweaking, but this works. Instead of removing the parent OR image (that threw exceptions), I've simply hidden the element ' var images = document.getElementsByTagName('img'); for (var i = 0; i < images.length; i++) { var img = images[i]; if (img.src.indexOf('comments') > 0){ img.style.display =「none」; } }' –

0

你可以試試這個

var imgs=document.images; 
for(i=0;i<imgs.length;i++) 
    if(imgs[i].src.test('comments')) 
     imgs[i].parentNode.parentNode.removeChild(imgs[i].parentNode);​ 

DEMO

0

感謝您的回覆。 lins05提出了一些我稍微調整過的代碼。注意:不是刪除元素或它的父項,下面的代碼只是隱藏元素。

var images = document.getElementsByTagName('img'); 
    for (var i = 0; i < images.length; i++) { 
     var img = images[i]; 
     if (img.src.indexOf('comments') > 0) { 
      img.style.display = "none"; 
     } 
    } 

rss feed的文章列表存儲在頁面上的模型中。這將是更理想的砍評論縮小模型..然而「每一個文章是頁面上的時間隱藏元素」目前的方法工作得很好:)