1

我有一个函数 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.">
4

2 回答 2

8
window.onload = function() {
    document.getElementById("image").src = getImgurUrl();
};
于 2012-07-15T13:51:22.637 回答
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;
于 2012-07-15T13:53:10.567 回答