使用jquery是否可以在div中查找和替换字符串?

时间:2015-07-23 04:48:53

标签: javascript jquery html css

我想创建一个脚本,用我的标记替换我想要的内容。

例如,我有这个div:

<div class="panel panel-!{status}!">
      <div class="panel-heading">
            <h3 class="panel-title"> !{title}! </h3>
      </div>
      <div class="panel-body">
            !{content}!
      </div>
</div>

我想使用jquery更改!{status}!!{title}!!{content}!内的文字。

有可能吗?或者,有没有比找到和替换方法更好的方法?

2 个答案:

答案 0 :(得分:2)

您可以将代码用作:

<div id="parentdivid">
    <div class="panel panel-!{status}!">
      <div class="panel-heading">
            <h3 class="panel-title"> !{title}! </h3>
      </div>
      <div class="panel-body">
            !{content}!
      </div>

    </div>
</div>    

$(document).ready(function() {
    var contentDiv = $("#parentdivid").html();
    contentDiv = contentDiv.replace(/!{title}!/g, 'title data');
    contentDiv = contentDiv.replace(/!{status}!/g, 'status data');
    contentDiv = contentDiv.replace(/!{content}!/g, 'content data');
    $("#parentdivid").html(contentDiv);
});

https://jsfiddle.net/k3syfvk5/1/

答案 1 :(得分:-1)

您可以使用Handlebars.js 对于演示,请在此处粘贴http://tryhandlebarsjs.com/

<强>模板:

 <div class="panel panel-{{status}}">
          <div class="panel-heading">
                <h3 class="panel-title"> {{title}} </h3>
          </div>
          <div class="panel-body">
               {{content}}
          </div>
    </div>

<强> JSON:

{ "title" : "title here","content": "content here","status": "status here" }

<强>输出:

<div class="panel panel-status here">
      <div class="panel-heading">
            <h3 class="panel-title"> title here </h3>
      </div>
      <div class="panel-body">
           content here
      </div>
</div>