JavaScript插入<img src="

时间:2017-09-12 18:28:37

标签: javascript html image

="" 时未加载图像我正在向表中添加行。对于每个新表项,picCell.innerHTML = '<label for="checkbox-a" data-form="ui-btn-up-a" class="'+uncheckedClassString+'" style="font-size: 200%; width: ' + tableCellWidth + 'px" id="' + checkBoxIdPreamble + index+'">' + itemString + ' <img src="' + picurl + '" width="30px" height="30px"/> </label>' 设置为:

itemString

picurl变量是表项的名称,setTimeout变量是我从Google登录中获取的用户个人资料图片的网址。

一切正常,但当Javascript运行以插入行时,用户的个人资料图像显示为:

plugins repo

控制台显示没有错误消息。

如果页面立即刷新,则图像显示正确:

enter image description here

有没有办法在插入行后立即加载图像?

3 个答案:

答案 0 :(得分:1)

您应该预先加载图像,然后在加载图像后渲染新行。这样,您就可以立即看到图像。

此外,您应该使用DOM API创建新的DOM元素。这将使您不必进行大量混乱的字符串连接。

最后,您可能希望提前设置CSS类,然后将这些类应用于元素,而不是使用JavaScript来创建内联样式(在可能的情况下应该尽可能避免)。

&#13;
&#13;
// Generate the image element first
var img = document.createElement("img");

// Configure the image's style
img.classList.add("customImgage");

// Set up a load event handler binding for the image
img.addEventListener("load", makeRow);

// Set up a load event handling function that will fire AFTER
// the image is loaded.
function makeRow() {

   // Create and configure the label
   var lbl = document.createElement("label");
   lbl.for = "checkbox-a";
   lbl.setAttribute("data-form", "ui-btn-up-a");
   lbl.classList.add(uncheckedClassString);
   lbl.style.width = tableCellWidth;
   lbl.id = checkBoxIdPreamble + index;
   lbl.textContent = itemString;
   
   // Append the image into the label. At this point, the image
   // is loaded and ready to be displayed.
   lbl.appendChild(img);
   
   // Append the label into the picCell
   picCell.appendChild(lbl);
}

// Preload the image. After this is done, the load event handler will fire
// causing makeRow to run, which will create the label, add the image to it
// and then insert the fully ready row and image into the DOM
img.src = picurl;
&#13;
.customImage {
  width:30px;
  height:30px;
}

.uncheckedClassString {
  font-size:200%;
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

预加载图片:

 var img=new Image();
    img.src=picUrl;

并在img标签中添加src。

picCell.innerHTML = '<label for="checkbox-a" data-form="ui-btn-up-a"
                        class="'+uncheckedClassString+'" 
                        style="font-size: 200%; width: ' +
                        tableCellWidth + 'px" 
                        id="' + checkBoxIdPreamble +
                        index+'">' + itemString + ' 
                   <img src="' + img.src + '" width="30px" 
                        height="30px"/>
                 </label>'

如果有帮助,请告诉我。

答案 2 :(得分:-2)

尝试在picurl之前添加斜杠。尝试类似下面的内容

picCell.innerHTML = '<label for="checkbox-a" data-form="ui-btn-up-a" class="'+uncheckedClassString+'" style="font-size: 200%; width: '+tableCellWidth+'px" id="'+checkBoxIdPreamble+index+'">'+itemString+' <img src="/'+picurl+'" width="30px" height="30px"/></label>'