0
我想用replace()来解析带有动态内容的模板变量。但是,当我使用$ .each()遍历替换数组时,替换似乎不起作用。没有什么被取代。这是我的代码:为什么我的替换方法不起作用?
var defaults = {
sample_div : '#sample-ref',
remove_button : '#removereference',
update_div : '#references',
add_button : '#addReference',
hidden_input : 'input[name="references"]'
};
var options = $.extend(defaults, options);
var new_ref = $('[name="reference"]').val();
var existing = $(options.hidden_input).val();
if(new_ref.length > 0){
existing = existing.split(',');
existing.push(new_ref);
var sample = $(options.sample_div).html();
var replacements = {
ref_int : existing.length,
ref_url : new_ref
}
$.each(replacements, function(index, value){
sample = sample.replace(/{index}/g, value);
});
$(options.update_div).append(sample);
}
这里是更详细的代码在jsFiddle。问题发生在第25行。
可能的重复[你如何将一个变量传递给正则表达式JavaScript?](http://stackoverflow.com/questions/494035/how-do-you-pass-a-variable-to-a-regular -expression-javascript) – 2014-11-05 22:09:05