我有一个阵列,比如
var acronyms = {
'NAS': 'Nunc ac sagittis',
'MTCP': 'Morbi tempor congue porta'
};
我需要找到每个首字母缩略词的第一个匹配,并通过jQuery包装标签
例如
<div id="wrap">NAS dui pellentesque pretium augue. MTCP pellentesque pretium augue. NAS ac ornare lectus MTCP nec.</div>
变得
<div id="wrap"><acronym title="Nunc ac sagittis">NAS</acronym> dui pellentesque pretium augue. <acronym title="Morbi tempor congue porta">MTCP</acronym> pellentesque pretium augue. NAS ac ornare lectus MTCP nec.</div>
感谢。
答案 0 :(得分:3)
您的数组实际上不是数组。这是一个javascript对象。这应该为你做。
测试实例: http://jsfiddle.net/c8tyK/
var acronyms = {
'NAS': 'Nunc ac sagittis',
'MTCP': 'Morbi tempor congue porta'
};
// Get the current text in the #wrap element
var current = $('#wrap').text();
// Iterate over the acronyms
for(var name in acronyms) {
// Create a new regular expression from the current key
// (You could actually skip this, and place 'name' directly
// in the replace() call)
var regex = new RegExp(name);
// Update the latest version of the current variable by doing
// a replace() on the first match
current = current.replace(regex, '<acronym title="' + acronyms[name] + '">' + name + '</acronym>');
}
// Insert the new value with HTML content
$('#wrap').html(current);
答案 1 :(得分:0)
var acronyms = {
'NAS': 'Nunc ac sagittis',
'MTCP': 'Morbi tempor congue porta'
};
content = $("#wrap").text();
$.each(acronyms, function (key, val) {
content = content.replace(key, "<acronym title=\"" + val + "\">" + key + "</acronym>")
});
$("#wrap").html(content);