Jquery:获取每个图像 src

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15060862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:17:56  来源:igfitidea点击:

Jquery: Get each image src

javascriptjqueryjquery-selectorseach

提问by MeltingDog

I have a series of images each with the class "photo";

我有一系列图像,每个图像都带有“照片”类;

I want to go through each of these and retrieve the photo source, for use later in an if statement. I have written the below code to do this, but have not been successful:

我想遍历其中的每一个并检索照片源,以便稍后在 if 语句中使用。我写了下面的代码来做到这一点,但没有成功:

$.each($(".photo"), function() {
  var imgsrc = $(this).attr("src").length;
  console.log(imgsrc);
});

I am not sure where I have gone wrong here. It seems to make sense to me, but I dont get anything in the console.

我不确定我在这里哪里出错了。这对我来说似乎很有意义,但我在控制台中没有得到任何东西。

Can anyone point me in the right direction?

任何人都可以指出我正确的方向吗?

回答by EnterJQ

If you have given same class name for all img tag then try this ,

如果您为所有 img 标签指定了相同的类名,那么试试这个,

  $(".photo").each(function() {  
   imgsrc = this.src;
   console.log(imgsrc);
  });  

回答by coolguy

$(document).ready(function(){
  $(".photo").each(function() {  
       imgsrc = this.src;
       console.log(imgsrc);
  });    
});

回答by Jai

May be you are missing doc ready handler:

可能是你失踪了doc ready handler

$(function(){
  $.each($(".photo"), function() {
    var imgsrc = $(this).attr("src").length;
    console.log(imgsrc); // logging length it should now print the length
  });
});

make sure to load this script first then your $.each()function:

确保先加载此脚本,然后再加载您的$.each()函数:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

回答by yoda

You are trying to read the lenghtof an object / array out of context here :

您正在尝试在lenght此处脱离上下文读取对象/数组的 :

var imgsrc = $(this).attr("src").length;

change to

改成

var imgsrc = $(this).attr("src");

edit: in order to check if the attribute exists

编辑:为了检查属性是否存在

if (imgsrc == undefined) { /* do something */ }