删除json中的额外<br/>标签

时间:2011-11-26 06:43:33

标签: jquery

我正在制作一个带有JSON的音乐列表进行搜索并在用户输入一些文本后立即显示。这是:

var music = [
{"name": "Abba"},
{"name": "Justin Bieber"},
{"name": "Taylor Swift"},
{"name": "David Guetta"},
{"name": "Usher"},
{"name": "LMFAO"},
{"name": "Enrique Iglesias"},
{"name": "Pitbull"},
{"name": "Eminem"},
{"name": "Nickelback"},
{"name": "Rihanna"},
{"name": "Queen"},
{"name": "Linkin Park"},
{"name": "Lady Gaga"},
{"name": "Gym Class Heroes"},
{"name": "Maroon 5"},
{"name": "heyhihello"},
{"name": "Paramore"},
{"name": "Owl City"},
{"name": "Black Eyed Peas"},
{"name": "Coldplay"},
{"name": "White Stripes"},
{"name": "Selena Gomez"},
{"name": "Selena Gomez and The Scene"},
{"name": "Creed"},
{"name": "Hinder"}

];
$(document).ready(function(){
sendm = function(txt){
var st = txt.toLowerCase();
if(st.length>0){
var res = new Array();
$.each(music, function(i, item) {
    if(item.name.substring(0, st.length).toLowerCase()===st){
       res[i] = item.name;
    }
});
document.getElementById("main-p").innerHTML = res.join("<br>");
}
};
});

现在,如果用户输入“Usher”,在结果中,由于
标签,它将留下几行。如何删除它们?

2 个答案:

答案 0 :(得分:1)

变化:

res[i] = item.name;

要:

res.push(item.name);

然后你的数组的长度将是找到的匹配数而不是找到的最后一个匹配的索引。

答案 1 :(得分:0)

而不是

$.each(music, function(i, item) {
    if(item.name.substring(0, st.length).toLowerCase()===st){
       res[i] = item.name;
    }
});

DO

$.each(music, function(i, item) {
    if(item.name.substring(0, st.length).toLowerCase()===st){
       res.push(item.name);
    }
});