2014-11-05 53 views
0

我想刪除主頁中文章div中每個描述中的{AC}。 每個div文章都有它的標題,圖片縮略圖和一些簡短的描述。在每個單一描述的開頭部分,我想刪除{AC}部分。所以我嘗試了下面的jQuery代碼,但不僅刪除了{AC},而且每篇div文章都有相同的描述。這是不需要的。你能幫我嗎?無法用jQuery刪除每篇文章div中描述文字的一部分

var descr = jQuery('.nspText').filter('.tleft').filter('.fleft'); 

descr.each(function(){ 

    jQuery(this).html(descr.html().replace('{AC}','')); 

}); 
+2

這將是更容易驗證,如果你有一個代碼片段,其中包括你在操作文本的樣本。 – Palpatim 2014-11-05 15:53:33

+0

html或jsfiddle幫助 – 2014-11-05 15:55:39

回答

3

你的代碼是接近的,但你的.each()循環只讀取第一個元素的HTML列表:

jQuery(".nspText.tleft.fleft").each(function() { 
    var $element = jQuery(this); 
    $element.html($element.html().replace("{AC}", "")); 
}); 

您代碼jQuery(descr)而不是jQuery(this)獲取的HTML。

一個稍微精簡的方式做到這一點:

jQuery(".nspText.tleft.fleft").html(function(index, oldHtml) { 
    return oldHtml.replace("{AC}", ""); 
}); 

.html()方法可以讓你傳遞一個功能,它會傳遞函數中的每個元素的索引中選擇的列表,再加上老該元素的HTML。返回值用作替代HTML。

+0

Thnx很多!它完美的作品! – Sergiti 2014-11-05 15:59:00

0

由於您沒有包含您正在操作的HTML,因此很難按照您的預期驗證此作品,但這裏有一個猜測。

var descr = jQuery('.nspText div' 
 
).filter('.fleft'); 
 

 
descr.each(function(){ 
 
    var $el = jQuery(this); 
 
    var html = $el.html(); 
 
    $el.html(html.replace('{AC}','')); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="nspText"> 
 
    <div class="tleft"> 
 
    <div class="fleft">This has the "AC" text right here: {AC}</div> 
 
    <div class="fleft">This has the "AC" text right here: {AC}</div> 
 
    <div class="fleft">This has the "AC" text right here: {AC}</div> 
 
    <div class="fright">This has the "AC" text right here, but isn't of class "fleft": {AC}</div> 
 
    <div class="fright">This has the "AC" text right here, but isn't of class "fleft": {AC}</div> 
 
    </div> 
 
</div>