document.querySelectorAll(“ a”)返回带有#url的空白节点列表

时间:2019-06-08 23:13:30

标签: javascript selectors-api

我有一些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;
    });  
  });
});

1 个答案:

答案 0 :(得分:0)

Gabriele Petrioli在评论中对其进行了修复。他说:

可能有些标签没有href。尝试使用m = document.querySelectorAll(“ a [href]”);