我有一些JavaScript,它将变量(c)的文本添加到由querySelectorAll(“ a”)标识的所有链接的href中。
这通常可以正常工作。
问题是,当我转到此页面的URL,并在其后添加任何带有井号/磅符号的字符时,例如“ #something”,querySelectorAll(“ a”)返回一个空的节点列表。这是我的代码:
$(document).ready(function() {
m = document.querySelectorAll("a");
m.forEach(function(item){
v = item.getAttribute("href");
item.setAttribute( "href", v.concat(window.c) );
});
})
这是我发现节点列表返回空白的方式:
<p id="p1"></p>
<script type="text/javascript">
$(document).ready(function() {
m = document.querySelectorAll("a");
m.forEach(function(item){
v = item.getAttribute("href");
document.getElementById("p1").innerHTML = v + " ";
item.setAttribute( "href", v.concat(window.c) );
});
})
</script>
这将在id =“ p1”段落中返回“ null”。
至少在Chrome中,当加载带有“#”的网址时,为什么至少在Chrome中querySelectorAll似乎不起作用?
更新:
certainPerformance希望我发布依赖于#的所有其他脚本,因此这里是:
/* This code adds or removes #_numbers to the end of the URL if the user clicks a accordion link */
if(window.location.href.indexOf("#") > -1) {
h = window.location.href.indexOf("#");
i = window.location.href.length;
j = window.location.href.substring(h, i);
x = j
}else{
x = "#_"
}
$(document).ready(function(){
$("#heading1").click(function(){
//when heading link is clicked, it toggles the section
$("#section1").toggle();
if(window.x.includes("1")){
//if x has a 1 in it, get rid of the 1
window.x = window.x.replace("1", "");
}
else{
window.x = window.x.concat("1"); //if x doesn't have a 1 in it, add a 1
}
window.x = window.x.replace("#_", ""); //remove multiple instances of #_ if there are any
y = "#_"
window.x = y.concat(window.x) // add #_ to the beginning of x
$('a[href]').each(function(){
var oldUrl = $(this).attr("href"); // set oldUrl to link above
if(oldUrl.includes("#_")){
oldUrl = oldUrl.replace("#_", "");
}
if(oldUrl.includes("1")){
oldUrl = oldUrl.replace("1", "");
}
var newUrl = oldUrl.concat(window.x); // for each link, concatenate it with x
$(this).attr("href", newUrl); // Set herf value
document.getElementById("heading1").href = window.x;
});
});
});
Gabriele Petrioli在评论中对其进行了修复。他说:
可能有些标签没有href。尝试使用m = document.querySelectorAll(“ a [href]”);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句