最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Setting img tag's src as the result of a javascript function - Stack Overflow

programmeradmin2浏览0评论

I have a function getImgurUrl() and I want what it returns to be the src value of a img tag.

How can I do this?

my function:

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;
}

and img tag:

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

I have a function getImgurUrl() and I want what it returns to be the src value of a img tag.

How can I do this?

my function:

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;
}

and img tag:

<img id="image" name="image" src=""  alt="If you're seeing this something is wrong.">
Share Improve this question edited Jul 15, 2012 at 13:50 Esailija 140k23 gold badges279 silver badges328 bronze badges asked Jul 15, 2012 at 13:46 A Clockwork OrangeA Clockwork Orange 24.8k7 gold badges28 silver badges30 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8
window.onload = function() {
    document.getElementById("image").src = getImgurUrl();
};
function getImageUrl(imageId) {
  return document[imageId].src;
}

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

I haven't tested this but you get the idea.

I'm not sure what you're doing with the cookie logic so just kept example simple.

--

I would remend you add jQuery to handle cross-browser patibility as getElementById or others may not work all the time and all versions, also document. might not as well and sometimes it's window.functionName()

In jQuery you would reference the image src similarly but in my return, you'd concat a pound symbol with the id:

return $('#' + id).src;
发布评论

评论列表(0)

  1. 暂无评论