//用于保存姓名首字母与姓名的键值对 var nameList = new Array(); //当页面加载完成后,初始化“nameList”。 window.onload = function(){ //提取ID为“divName”中的所有姓名 var div = document.getElementById("divName"); if (div){ var names = []; //兼容Firefox与Chrome; if (div.textContent){ //通过replace(/\s/ig," ")将所有空白字符,包括空格、制表符、换页符等等都替换为空格 names = div.textContent.replace(/\s/ig," ").split(" "); }else{ names = div.innerText.replace(/\s/ig," ").split(" "); } for (var i = 0; i < names.length; i++){ if (names[i] != ""){ //获取拼音首字母缩写 var arrRslt = makePy(names[i]); //将拼音与中文的对应关系添加到数组中 nameList.push(new Array(arrRslt.toString(), names[i])); } } } }
执行查找代码: