简体   繁体   English

渲染Java脚本的HTML模板

[英]render a HTML template for Javascript

HTML Code: HTML代码:

<form id="add_post">
    <div id="post-add-tag">
        <div class="input-group">
            <input type="text" id="post_tags" name="post_tags" />
            <span class="input-group-btn">
                <button id="add_tag_button" type="submit">Add</button>
            </span>
        </div>
        <ul id="tags_list"></ul>
    </div>
</form>

PHP code that prints this scripts into footer: 将以下脚本打印到页脚的PHP代码:

function post_tag_template(){
    ?>
    <script type="text/template" id="the_template">
        <li>
            <input type="hidden" name="items[]" value="{{= stripHTML(name) }}" />
            {{= stripHTML(name) }}
        </li>
    </script>
    <script type="text/javascript">
        function stripHTML(html)
        {
           var tmp = document.createElement("DIV");
           tmp.innerHTML = html;
           return tmp.textContent||tmp.innerText;
        }
    </script>
    <?php
}

and this is the javascript code: 这是javascript代码:

function addTag(tag) {
    var form        = $('form#add_post'),
        tags_list   = form.find('ul#tags_list'),
        source      = $('#the_template').html();    

    tags_list.append(source);
}

$(document).on('click', 'form#add_post #add_tag_button', function(e) {
    e.preventDefault();

    addTag( $('input#post_tags').val() );
});

What are my codes do? 我的代码是做什么的?

My codes print the content of template #the_template without replace #{{= stripHTML(name) }} with the tag name (The value of input #post_tags ). 我的代码打印模板#the_template的内容,而不用标签名(输入#post_tags的值#{{= stripHTML(name) }}替换#{{= stripHTML(name) }}

What do I need to do? 我需要做什么?

I want when I click on #add_tag_button get the template content #the_template and replace {{= stripHTML(name) }} with the tag name (The value of input #post_tags ). 我想在单击#add_tag_button获取模板内容#the_template并将{{= stripHTML(name) }}替换为标签名称(输入#post_tags的值)。

try this: 尝试这个:

function post_tag_template(){
    ?>
    <script type="text/template" id="the_template">
        <li>
            <input type="hidden" name="items[]" value="{{PlainName}}" />
            {{PlainName}}
        </li>
    </script>
    <script type="text/javascript">
        function stripHTML(html)
        {
           var tmp = document.createElement("DIV");
           tmp.innerHTML = html;
           return tmp.textContent||tmp.innerText;
        }
    </script>
    <?php
}    

Javascript code: JavaScript代码:

    function addTag(tag) {
    var form        = $('form#add_post'),
        tags_list   = form.find('ul#tags_list'),
        source      = $('#the_template').html();   

   var search1 = /{{PlainName}}/g;
    tags_list.append(source.replace(search1, stripHTML(name)}

Since you have multiple replace elements, you should use Regx. 由于您有多个替换元素,因此应使用Regx。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM