2016-02-10 38 views
-1

如何用另一個字符串(url)替換使用javascript的html代碼塊中的標籤(| mybackground |)?用javascript替換html代碼中的字符串

我正在一個WordPress站點的塊中工作。我有一個很大的html電子郵件模板。所以我希望得到它,將標記更改爲url,然後將其作爲emailcontent發送給用戶。它必須改變,因爲每個用戶都會得到他的個性化圖片,並且他們都有不同的名字。但我想用1個基本模板(其實我有一整個HTML的emailTemplate有很多代碼,但我只是後一個片段在這裏。)

<div id="emailcontent"> 
    <table> 
    <tr> 
     <td style="background-image: url('|mybackground|');"> 

     ...some content... 

     </td> 
    </tr> 
    </table> 
</div> 

回答

0

給你td一個ID,並使用document.getElementById("yourId").setAttribute("background", "[www.yourUrl.com]")

0

您不會在HTML中替換字符串。這是非常糟糕的做法。

VML是no longer supported by IE10+這樣你就可以刪除代碼(它甚至不完整的,因爲你甚至不必AV:文本開始) - 我固定的,但你仍然可以將其刪除:

<!--[if gte mso 9]> 
    <v:rect xmlns:v="urn:schemas-microsoft-com:vml" fill="true"> 
    <v:fill type="frame" src="|mybackground|" position="0,0" /> 
    </v:rect> 
<![endif]--> 

反而做這樣的事情。

$(function() { 
 
    var card = "X", // where to get card from? 
 
     $td = $("#emailcontent").find("td[background='|mybackground|']"), 
 
     img = $("#"+card).attr('src'); 
 
    $td.attr("background",img); 
 
    $td.attr("style",$td.attr("style").replace("|mybackground|",img)); 
 
});
#X { display:none } 
 
td { height:200px; width:200px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div id="emailcontent"> 
 
    <table> 
 
    <tr> 
 
     <td background="|mybackground|" style="background-image: url('|mybackground|');">Here is an elephant</td> 
 
    </tr> 
 
    </table> 
 
    <hr/> 
 
    <img id="X" src="http://d5prcm06amy2t.cloudfront.net/mobile/mobile-hank04-shadow.png"/> 
 
</div>

0

MDN

要執行全局搜索和替換,或者包括克開關在 正則表達式,或者如果第一個參數是一個字符串,在flags參數中包含 g。

所以,即使這是髒東西,就這個樣子應該工作:

var find = '\\|mybackground\\|'; 
 
var re = new RegExp(find, 'g'); 
 
document.body.innerHTML = document.body.innerHTML.replace(re, $("#card").attr('src'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="emailcontent"> 
 
    <table> 
 
    <tr> 
 
     <td background="|mybackground|" style="background-image: url('|mybackground|');"> 
 
    
 
     </td> 
 
    </tr> 
 
    </table> 
 
</div> 
 
<img id="card" src="mysource">