document.querySelector使用javascript为html注入返回null

时间:2018-05-25 16:42:48

标签: javascript html css

修改上一个问题,因为我认为我已经发现了具体问题。我通过javascript注入一些html,代码如下:

    var clickFn = function(e) {
    console.log("click registered");
    e.preventDefault();
    //console.log("id is" + " " + this.id);
    dropdown.classList.remove("open");
    btn.innerHTML = this.text;
    var activeLink = document.querySelector(".option .active");

    searchBoxes = parseInt(this.id);
    inputFieldHTML = [];

    for(i=0; i<searchBoxes; i++) {
      //j = i +1;
      inputFieldHTML.push('<input placeholder="Search" class="Box" type="text" id="gearInput' + i + '"' + "/>" + '<div class="ccontainer"><div class="cdropdown"> <button class="ctitle"><span class="cselectorText">dynamically injeced menu</span></button> <ul class="cdropdown-options"> <li class="coption"><a href="#">option 1</a></li> <li class="coption"><a href="#">option2</a></li></ul></div></div></div>' );
    }


    document.getElementById("inputBoxes").innerHTML = inputFieldHTML.join("");

    if (activeLink) {
      activeLink.classList.remove("active");
    }

    this.classList.add("active");
};

for (var i = 0; i < optionLinks.length; i++) {
   optionLinks[i].addEventListener("mousedown", clickFn, false);
}

创建这些元素后,我需要创建以下对象:

var coptionLinks = document.querySelectorAll(".coption a");
var cbtn = document.querySelector(".ctitle");
var cdropdown = document.querySelector(".cdropdown-options");

这些都返回null,因为它们在被前一个循环创建之前被设置。我怎样才能确保在for循环完成后设置它们。

1 个答案:

答案 0 :(得分:0)

I don't get null values.这个例子与你的有多远?

<强> HTML

<div id="inputBoxes"></div>

<强> JS

(function() {

var inputFieldHTML = [];

for(i=0; i<3; i++) {
      //j = i +1;
      inputFieldHTML.push('<input placeholder="Search" class="Box" type="text" id="gearInput' + i + '"' + "/>" + '<div class="cdropdown"> <button class="ctitle"><span class="cselectorText">Dynamically Generated Selector</span></button> <ul class="cdropdown-options"> <li class="coption"><a <href="#">option 1</a></li> <li class="coption"><a <href="#">option 2</a></li></ul></div</div>')
   }
 document.getElementById("inputBoxes").innerHTML = inputFieldHTML.join("");

var coptionLinks = document.querySelectorAll(".coption a");
var cbtn = document.querySelector(".ctitle");
var cdropdown = document.querySelector(".cdropdown-options");

console.log(coptionLinks);
console.log(cbtn);
console.log(cdropdown);

})()