没有jQuery,如何在iframe中按标题获取元素?

时间:2019-05-15 14:18:41

标签: javascript jquery

我在jQuery中遇到一些性能问题。因此,我想尝试使用JS而不是jQuery的最长长度为7000的循环。因为我读过,那个jQuery总是表现很差。

我试图将jQuery选择器转换为JS,但仍然无法正常工作:

来自:

var i;
for (i = 0; i < e.detail.length; i++){
    $("iframe").contents().find(".timeline-node[title='" + i + "']").css("background-image", "url( \"imgs/" + e.detail[i] + ".png \") ");
}

至:

var i;
for (i = 0; i < e.detail.length; i++){
   document.getElementById('#iframe').querySelector("[title=\"" + i + "\"]").css("background-image", "url( \"imgs/quality_3/" + e.detail[i] + ".png \") ");
}

我的新代码的错误是:无法读取HTMLDocument的null属性'querySelector'。 我认为JS找不到attr的标题。一世。但是我的jQuery代码效果很好,但是需要80秒。可以处理7000个索引。

2 个答案:

答案 0 :(得分:3)

仅查询iframe一次

var i, iframe = document.querySelector('iframe').contentWindow.document;
for (i = 0; i < e.detail.length; i++){
   iframe.querySelector("[title=\"" + i + "\"]").style.backgroundImage = "url( \"imgs/quality_3/" + e.detail[i] + ".png \") ";
}

您可以尝试仅使用一个查询并过滤结果

document.querySelector("iframe").contentWindow.document.querySelectorAll("[title]").forEach(function (elm) {
    var id = +elm.getAttribute("title");
    if (id < e.detail.length) {
        elm.style.backgroundImage = "url( \"imgs/quality_3/" + e.detail[id] + ".png \") ";
    }
});

多iframe版本

document.querySelectorAll("iframe").forEach(function (iframe) {
    iframe.contentWindow.document.querySelectorAll("[title]").forEach(function (elm) {
        var id = +elm.getAttribute("title");
        if (id < e.detail.length) {
            elm.style.backgroundImage = "url( \"imgs/quality_3/" + e.detail[id] + ".png \") ";
        }
    })
});

性能比较

console.time("loop");
var i;
for(var a = 0; a < 10; a++) {
  for (i = 0; i < 20; i++){
     document.querySelector("[title=\"" + i + "\"]");
  }
}
console.timeEnd("loop")

console.time("singleQuery");
var i;
for(var a = 0; a < 10; a++) {
   document.querySelectorAll("[title]").forEach(function(elm) { 
     if(+elm.getAttribute("title") < 20) { 
      // change background 
     }
   });
}
console.timeEnd("singleQuery")
<p title="0"></p>
<p title="1"></p>
<p title="2"></p>
<p title="3"></p>
<p title="4"></p>
<p title="5"></p>
<p title="6"></p>
<p title="7"></p>
<p title="8"></p>
<p title="9"></p>
<p title="10"></p>
<p title="11"></p>
<p title="12"></p>
<p title="13"></p>
<p title="14"></p>
<p title="15"></p>
<p title="16"></p>
<p title="17"></p>
<p title="18"></p>
<p title="19"></p>

答案 1 :(得分:-3)

document.getElementById('#iframe')

选择一个ID为“ #iframe”的元素。 “#”是ID的Jquery选择器,因此您需要省略“#”并使用

选择iframe
document.getElementById('iframe')