0

我一直在研究一个简单的 jQuery 插件,它基本上是模板 json 数据。它允许您提供 html 模板 url、数据 url 和目标,用于您希望显示数据的位置。我遇到的问题是,当我这样做时:

var regex = new RegExp( '[['+ key +']]', 'g' );
tplHTML = tplHTML.replace( regex, this[key] );

它只是替换它找到的第一个案例,而不是跟随全局标志。

这是调用插件并显示数据的页面:

<!DOCTYPE html>
<head>
<title></title>

<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,700,600' rel='stylesheet' type='text/css'>

<style>
* { font-family: 'Open Sans', sans-serif; color: #666; font-weight: 100; line-height: 150%; font-size: 1.0em; }
.container { width: 960px; margin: 0 auto; padding: 10px; border: 1px solid #ccc; }
    .left { width: 460px; float: left; }
    .right { width: 400px; float: right; }

td, th { text-align: left; vertical-align: top; border: 1px solid #f5f5f5; padding: 10px; font-size: .8em; }
.clear { clear: both; }
</style>

</head>
<body>

<div class="container">
    <div class="left">
        <table id="users">
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Phone</th>
            </tr>
        </table>
    </div>
    <div class="right">
        <table id="comments">
            <tr>
                <th>ID</th>
                <th>User id</th>
                <th>Comment</th>
                <th>Date</th>
            </tr>
        </table>
    </div>

    <div class="clear"></div>
</div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="js/userData.js"></script>
<script src="js/templatize.ajax.js"></script>

<script>
$('#users').templatize({
    itemsURL: 'process/ajaxUsers.php?l=5&order=ASC',
    tplURL: 'tpl/usersTpl.php',
    targetHTML: '#users'
});

$('#comments').templatize({
    itemsURL: 'process/ajaxComments.php?l=5&order=ASC',
    tplURL: 'tpl/commentTpl.php',
    targetHTML: '#comments'
});
</script>

</body>
</html>

这是插件代码:

( function ( $ ) {

    $.fn.templatize = function( options ) {

        /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    Configuration Settings    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
        var config = $.extend({
            debugging           :       false,
            targetHTML          :       '.container',
            output              :       '',
            tplURL              :       '',
            itemsURL            :       '',
            tpl                 :       '',
            items               :       ''
        }, options );

        init();

        /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    Initialize & Retrieve Data Objects    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
        function init() {

            var tpl, itemsObj;

            $.ajax({
                type: "GET",
                url: config.tplURL,
                data: 'json',
                async: false,
                success: function( info ) {
                    tpl = info; 
                }
            });

            $.ajax({
                type: "GET",
                url: config.itemsURL,
                data: 'json',
                async: false,
                success: function( items ) {
                    itemsObj = items;   
                }
            });

            config.tpl = tpl;
            config.items = itemsObj; 

            templatize();

        }

        /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%    Receive Data & Replace tags for template    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
        function templatize() {

            var tplHTML = ''; 
            var i = jQuery.parseJSON( config.items );

            if( config.debugging ) {
                console.log( i );
            }

            $( i ).each( function() {

                tplHTML = config.tpl;

                for (var key in this) {

                    //tplHTML = tplHTML.replace('[['+ key +']]', this[key]);
                    var regex = new RegExp( '[['+ key +']]', 'g' );
                    tplHTML = tplHTML.replace( regex, this[key] );

                }

                config.output += tplHTML;
            });

            $( config.targetHTML ).append( config.output );

            if( config.debugging ) {
                console.log( 'Target for data placement: '+ config.targetHTML );
            }

        }

    };

}) ( jQuery );

最后是模板代码:

<tr><td>[[id]]</td><td><a href="user.php?id=[[id]]">[[name]]</a></td><td>[[email]]</td><td>[[phone]]</td></tr>

我正在使用类似于 smarty 标签的类似标签结构格式。我一直在为此绞尽脑汁并研究各种文档,但没有找到适合我的解决方案。任何帮助将不胜感激!

总的来说,我只需要找出一种方法来获取 javascripts .replace() 方法来不仅替换匹配的第一个实例,而且替换所有实例。我尝试了一个似乎只与 Firefox 兼容的版本,其中 .replace(search, replacement, flags)

谢谢

4

1 回答 1

3

首先,我认为您希望您的正则表达式使用变量key而不是字符串"key",所以它应该是:

new RegExp( '[[' + key + ']]', 'g' )

其次[,在正则表达式中具有特殊含义,因此需要对其进行转义:

new RegExp( '\\[\\[' + key + ']]', 'g' )

因为你是从一个字符串构建你的正则表达式,所以你需要一个双反斜杠来转义每个反斜杠,[这样对于 a keyof 来说"id",生成的正则表达式将是\[\[id]].

于 2013-08-04T02:26:05.580 回答