Javascript:get< img> src并设置为变量? [英] Javascript : get <img> src and set as variable?
问题描述
如果下面的img存在
<img id="youtubeimg" src="http://i1.ytimg.com/vi/VK4ah66jBvE/0.jpg"/>
且脚本是
<script>
var youtubeimgsrc = "something here"
document.write(''+youtubeimgsrc+'')
</script>
,结果应为 http://i1.ytimg.com/ vi / VK4ah66jBvE / 0.jpg
我该怎么做才能获得图像源并设置为变量。
what can i do to get the image source and set as a variable.
推荐答案
只要脚本 img
之后,那么:
As long as the script is after the img
, then:
var youtubeimgsrc = document.getElementById("youtubeimg").src;
参见 getElementById
。
如果脚本是之前的 img
,那么当然 img
不会还存在,但这不起作用。这就是为什么许多人建议将脚本放在 body
元素末尾的原因之一。
If the script is before the img
, then of course the img
doesn't exist yet, and that doesn't work. This is one reason why many people recommend putting scripts at the end of the body
element.
附注:在您的情况下,因为您使用了绝对URL,但是如果您在属性中使用了 relative URL,则无关紧要,如下所示:
Side note: It doesn't matter in your case because you've used an absolute URL, but if you used a relative URL in the attribute, like this:
<img id="foo" src="/images/example.png">
... src
反映属性将是已解决的网址&nd;—也就是说,变成的绝对URL。所以如果它在页面 http://www.example.com
, document.getElementById(foo)。src
会给你http://www.example.com/images/example.png
。
...the src
reflected property will be the resolved URL — that is, the absolute URL that that turns into. So if that were on the page http://www.example.com
, document.getElementById("foo").src
would give you "http://www.example.com/images/example.png"
.
如果您希望 src
属性的内容不是而未经解析,则使用 getAttribute
而是: document.getElementById(foo)。getAttribute(src)
。这会给你/ images / example.png
以上我的例子。
If you wanted the src
attribute's content as is, without being resolved, you'd use getAttribute
instead: document.getElementById("foo").getAttribute("src")
. That would give you "/images/example.png"
with my example above.
如果你有绝对的话网址与问题中的网址一样,没关系。
If you have an absolute URL, like the one in your question, it doesn't matter.
这篇关于Javascript:get< img> src并设置为变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!