动态str替换为包含流的html上的javascript

时间:2012-08-22 15:37:15

标签: javascript jquery string replace

我有一个看起来大致像这样的HTML

<div id="wallPostTemplate">
    <li id='comment-content--oOo-id-oOo-' class='comment-content' comment_id='-oOo-id-oOo-'>
        <a class='comment-avatar' href='-oOo-link-oOo-'>
            <img class='small_avatar' src='<?="../" . MESTO_ZA_UPLOAD_FAJLOVA_KORISNIKA ?>-oOo-korisnikPodaci.Slika-oOo-'></a> 
            -oOo-text-oOo-
    </li>
</div>

现在我将html的内容变为带有$('#wallPostTemplate').text()的sting,然后我想动态替换字符串-oOo-id-oOo-的出现次数 我存储的任何数据都包括-oOo-id-oOo--oOo-text-oOo-之类的变量,等等......

现在我尝试了很多方法来解决这个问题,但我总是没有解决方案。 这是我最近的尝试。帮助请Q_Q

var regex = new RegExp('{\-oOo\-'+index+'\-oOo\-}', "g");
post = post.replace(regex, value);  

我也试过str.replace但它不起作用......似乎新线条是问题,但我不知道如何过来......

编辑:

为了让它更容易理解我在jsfidle上做了一个例子:http://jsfiddle.net/DdBFB/ 正如你所看到的,你什么都看不见......当你通过html函数得到内容时,它不起作用。

3 个答案:

答案 0 :(得分:1)

如果我理解你的问题,你的目标是制作一个类似于将在运行时/客户端加载的帖子模板。因此,如果这确实是您的目标,您可以尝试使用jQuery Template Plugin

您的案例样本:(尚未测试)

var tmlpPost = "<div id='${postId}'>" + 
                         "      <li id='comment-content-${postId}' class='comment-content' comment_id='${postId}'>" + 
                         "              <a class='comment-avatar' href='${link}'>" + 
                         "                  img class='small_avatar' src='<?="../" . MESTO_ZA_UPLOAD_FAJLOVA_KORISNIKA ?>${korisnikPodaciSlika}'>" + 
                         "              </a> " + 
                         "              ${postText}" + 
                         "      </li>" + 
                         "</div>";


$.tmpl( tmlpPost, { "postId" : "123" , "link" : "http://posturl.com", "korisnikPodaciSlika" : "something",  "postText" : "Post text goes here..."}).appendTo( "#yourPostWall" );

或使用<script>而不是varSee this Fiddle

<script id="tmlpPost" type="text/x-jquery-tmpl">
    <div id='${postId}'>
          <li id='comment-content-${postId}' class='comment-content' comment_id='${postId}'>
                  <a class='comment-avatar' href='${link}'>
                      <img class='small_avatar' src='<?="../" . MESTO_ZA_UPLOAD_FAJLOVA_KORISNIKA ?>${korisnikPodaciSlika}'>
                  </a>
                  ${postText}
          </li>
    </div>
</script>

现在页面加载:

$("#tmlpPost").tmpl( { "postId" : "123" , "link" : "http://posturl.com", "korisnikPodaciSlika" : "something",  "postText" : "Post text goes here..."}).appendTo( "#output" );​

答案 1 :(得分:0)

虽然你的问题不是很清楚我已经掀起了一个基于正则表达式替换值的例子。

var source = "-oOo-korisnikPodaci.Slika-oOo-";
var id = "korisnikPodaci.Slika";
var regex = new RegExp('\-oOo\-' + id + '\-oOo\-', "gmi");

// Match
source.replace(regex, "hello world"); // => "Hello World"

// Mismatch
source = "-oO!!!o-korisnikPodaci.Slika-oO!!!o-";
source.replace(regex, "hello world"); // => "-oO!!!o-korisnikPodaci.Slika-oO!!!o-"

答案 2 :(得分:0)

好吧,我认为答案是我设置了正则表达式标志错误,所以我去了jsfiddle并摆弄它,你可以在那里看到答案:)

http://jsfiddle.net/DdBFB/11/

我错过了多行标志Q_Q ....即使在php中也没有用正则表达式来表达不好用js ...