2016-02-10 35 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">