所以我有这个svg地图,其中的街道都在id标签中包含街道名称。我希望有一个Searchfield,它通过将searchinput与街道的ID部分匹配来搜索街道。现在我的代码有一些问题。首先,它使用区分大小写的字母进行搜索,其次,每个空格的ID都带有下划线,搜索时需要用空格代替。最后,当我进行正向搜索时,它会为街道上色,但是如果我删除了搜索,则街道会一直带有突出显示的颜色。
document.onkeydown = function(event){
var searchvalue = document.getElementById("searchfield").value;
document.querySelector("[id*="+searchvalue+"]").style.stroke = "yellow";}
Now i lookedup some solutions and one is to make a for loop that checks every element for these criteria,但是我的svg包含多个标记名,例如“ line”,“ path”和“ polygon”,所以我不知道该怎么做。
答案 0 :(得分:4)
这里需要的是将类分配给搜索项,然后在下次搜索时从所有突出显示的路径中删除样式和该类。对于搜索,首先用空格分隔路径,然后大写字符串,然后再次用下划线将其连接起来,即
function changeFunction(event){
console.log(event);
var searchvalue = event.split(' ').map(element => element.charAt(0).toUpperCase() + element.slice(1).toLowerCase()).join('_');
document.querySelectorAll('.searched').forEach(element => {
element.removeAttribute('style');
element.removeAttribute('class');
});
if(searchvalue) {
document.querySelectorAll("[id*="+searchvalue+"]").forEach(( element) => {
element.style.stroke = "green";
element.setAttribute('class', 'searched');
});
}
}