将img标签的src设置为javascript函数的结果

时间:2012-07-15 13:46:49

标签: javascript html function image src

我有一个函数getImgurUrl(),我希望它返回的是img标记的src值。

我该怎么做?

我的职能:

function getImgurUrl() {
    //get imgur url for current image
    var cookieArray = document.cookie.split(";");
    var encodedURL = cookieArray[2].split("=");
    var decodedURL = decodeURIComponent(encodedURL[1]);
    return decodedURL;
}

和img标签:

<img id="image" name="image" src=""  alt="If you're seeing this something is wrong.">

2 个答案:

答案 0 :(得分:8)

window.onload = function() {
    document.getElementById("image").src = getImgurUrl();
};

答案 1 :(得分:0)

function getImageUrl(imageId) {
  return document[imageId].src;
}

<img id="mike" src="http://yoursite.com/images/1.jpg" />

我没有测试过这个,但你明白了。

我不确定你在使用cookie逻辑做什么,所以保持简单的例子。

-

我建议您添加jQuery来处理跨浏览器兼容性,因为getElementById或其他人可能无法一直工作,所有版本也都是文档。可能不太好,有时它是window.functionName()

在jQuery中你会同样引用图像src,但是在我的回报中,你会用一个带有id的英镑符号:

return $('#' + id).src;