简体   繁体   English

使用 javascript 获取 img src

[英]Get an img src using javascript

Pardon my ignorance but can the getHref function be applied to returning an img src?请原谅我的无知,但getHref function 可以应用于返回 img src 吗?

I'd like to get the url for the image below我想获得下图的 url

<div class="uk-width-medium-3-10 uk-text-center">
  <img src="/images/saleitems/Toaster.svg" class="uk-border-circle" alt="great toaster">
</div>

I have this working for a breadcrumb URL...我有这个为面包屑 URL 工作...

function getHref() {
  return document.querySelectorAll('.uk-breadcrumb li a')[1].href;
}

My sad attempt at adjusting the above ( which didn't work)我调整上述内容的悲伤尝试(没有用)

function getHref() {
  return document.querySelectorAll('.uk-border-circle li a')[0].href;
}

It should return它应该返回

https://www.example.com/images/saleitems/Toaster.svg

Any help or suggestions here would be appreciated任何帮助或建议将不胜感激

I think your selector isn't correct, you are targeting an a element when you actually want to target the img element, additionally, if you expect a single element to be selected, you can use querySelector instead of querySelectorAll .我认为您的选择器不正确,当您实际想要定位img元素时,您定位的是a元素,此外,如果您希望选择单个元素,您可以使用querySelector而不是querySelectorAll

Another thing is what you're looking for is the img 's src attribute.另一件事是您正在寻找的是imgsrc属性。
An href attribute is what you would look for if your element was indeed an a tag如果你的元素确实是一个a标签,你会寻找一个href属性

// returns https://www.example.com/images/saleitems/Toaster.svg
document.querySelector('.uk-border-circle').src

It should work:它应该工作:

function getHref() {
      return document.querySelectorAll('.uk-breadcrumb')[1].src;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM