简体   繁体   English

document.querySelector为使用javascript的html返回null

[英]document.querySelector returning null for html inject with javascript

Revising a previous question as I think I have discovered what the specific issue is. 我想我已经发现了具体的问题,所以修改了先前的问题。 I am injecting some html via javascript with the following code: 我通过以下代码通过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);
}

After those elements are created I need to create the following objects: 创建这些元素之后,我需要创建以下对象:

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

These are all returning null as they are being set before being created by the previous loop. 这些都返回空值,因为它们是在上一个循环创建之前设置的。 How can I ensure I set these after the for loop has completed. 我如何确保在for循环完成后进行设置。

I don't get null values. 我没有空值。 In how far does this example differ from yours? 该示例与您的示例有多大区别?

HTML 的HTML

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

JS 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);

})()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM