【发布时间】:2019-06-08 23:13:30
【问题描述】:
我有一些 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 中,为什么 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;
});
});
});
【问题讨论】:
-
听起来 DOM 依赖于哈希(这很容易用 JS 完成),虽然没有minimal reproducible example,但不可能 100% 确定发生了什么
-
我该怎么做?
-
理想情况下,通过发布重现您所描述行为的代码(查看代码应该让事情变得显而易见 - 代码执行某些操作,或者代码不同,具体取决于哈希)
-
thanks.....posted.....errr,警告,这个附加代码是一堆臭垃圾
-
可能有一些
a标签没有href。尝试使用m = document.querySelectorAll("a[href]");