Javascript set img src

我可能遗漏了一些简单的东西,但是当你读到的所有东西都不能正常工作的时候,这是相当恼人的。我有图像,可以在一个动态生成的网页过程中复制多次。所以显而易见要做的就是预加载它并且一直使用这个变量作为源。

var searchPic;
function LoadImages() {
searchPic = new Image(100,100);
searchPic.src = "XXXX/YYYY/search.png";
// This is correct and the path is correct
}

然后我使用

  document["pic1"].src = searchPic;

或者

  $("#pic1").attr("src", searchPic);

但是,图像从来没有正确设置在 FireBug 当我查询的图像,我得到的 [object HTMLImageElement]作为图像的 src

在 IE 中我得到:

http://localhost:8080/work/Sandbox/jpmetrix/[object]
451289 次浏览

您应该使用以下命令设置 src:

document["pic1"].src = searchPic.src;

或者

$("#pic1").attr("src", searchPic.src);
document["pic1"].src = searchPic.src

应该可以

你得准备好

document["pic1"].src = searchPic.src;

SearchPic 本身就是您的 Image () ,您需要读取您设置的 src。

You don't need to construct a whole new image... the src attribute just takes a string value :-)

Instances of the image constructor are not meant to be used anywhere. You simply set the src, and the image preloads...and that's it, show's over. You can discard the object and move on.

document["pic1"].src = "XXXX/YYYY/search.png";

is what you should be doing. You can still use the image constructor, and perform the second action in the onload handler of your searchPic. This ensures the image is loaded before you set the src on the real img object.

像这样:

function LoadImages() {
searchPic = new Image();
searchPic.onload=function () {
document["pic1"].src = "XXXX/YYYY/search.png";
}
searchPic.src = "XXXX/YYYY/search.png"; // This is correct and the path is correct
}

您的 src 属性是一个对象,因为您将 src 元素设置为您在 JavaScript 中创建的整个图像。

试试看

document["pic1"].src = searchPic.src;

哇! 当你使用 src,那么 searchPicsrc也必须使用。

document["pic1"].src = searchPic.src

看起来好多了

另外,解决这个问题的一种方法是使用 document.createElement并创建 html IMG,然后像这样设置它的属性。

var image = document.createElement("img");
var imageParent = document.getElementById("Id of HTML element to append the img");
image.id = "Id";
image.className = "class";
image.src = searchPic.src;
imageParent.appendChild(image);

备注 : 有一点是 Javascript 社区现在鼓励开发人员使用诸如 querySelectorgetElementByIdgetElementsByClassName之类的文档选择器,而不是文档[“ pic1”]。

If you're using WinJS you can change the src through the Utilities functions.

WinJS.Utilities.id("pic1").setAttribute("src", searchPic.src);

纯 JavaScript 手动创建 img标签和 add attributes,

var image = document.createElement("img");
var imageParent = document.getElementById("body");
image.id = "id";
image.className = "class";
image.src = searchPic.src;            // image.src = "IMAGE URL/PATH"
imageParent.appendChild(image);

pic1中设置 src

document["#pic1"].src = searchPic.src;

或者用 getElementById

document.getElementById("pic1").src= searchPic.src;

J-Query 来归档,

$("#pic1").attr("src", searchPic.src);