如何在jQuery中使用占位符?

时间:2012-04-25 20:46:54

标签: javascript jquery jquery-plugins

我想创建一个文本模板并在其中设置占位符并填充此占位符并在我的页面中使用它? 喜欢..

var temp = '<div class="persons">';
temp += '<p> <span class="firstname">First Name :</span> <span> [firstname]</span> </p>';
temp += '<p> <span class="lastname">Last Name :</span> <span> [lastname]</span> </p>';
temp += '<p> <span class="tel">Telephone :</span> <span> [tel]</span> </p>';
temp += '</div>';

并使用我的值更改[firstname][lastname][tel]并在页面中显示? 或任何其他想法?

4 个答案:

答案 0 :(得分:3)

快速&amp;脏JS模板引擎:

// Create a matching object for each of your replacement
var matches = {
    "[firstname]": "fred",
    "[lastname]": "smith",
    "[tel]": "123456789"
}

// Loop through the keys of the object
Object.keys( matches ).forEach( function( key ) {
    // Replace every key with its value
    temp = temp.replace( key, matches[ key ] )
} )

答案 1 :(得分:2)

你可以简单地替换它们。

temp.replace("[firstname]", "fred").replace("[lastname]", "smith").replace("[tel]", "123456789");

不确定您是否使用jQuery模板。

答案 2 :(得分:2)

您是否尝试过.replace()

http://jsfiddle.net/KL9kz/

答案 3 :(得分:1)

尝试这样的,非常基本的

function replaceall(tpl, o, _p, p_) {
    var pre = _p || '%',
        post = p_ || '%',
       reg = new RegExp(pre + '([A-z0-9]*)' + post, 'g'),
        str;
    return tpl.replace(reg, function (str, $1) {
        return o[$1];
    });
};
var temp = '<div class="persons">'+
        '<p> <span class="firstname">First Name :</span> <span> [firstname]</span> </p>'+
        '<p> <span class="lastname">Last Name :</span> <span> [lastname]</span> </p>'+
        '<p> <span class="tel">Telephone :</span> <span> [tel]</span> </p>'+
    '</div>',
    data = {
        'firstname':'Fede',
        'lastname':'Ghe',
        'tel' : '+00 012 3456789' 
    };
alert(replaceall(temp, data, '\\\[', '\\\]'));

小心逃避占位符边界并根据需要调整内部正则表达式 希望它有所帮助

相关问题