jQuery 在div中获取图像属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8643165/
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-27 10:49:06  来源:igfitidea点击:

Get image attrib inside a div?

jqueryfind

提问by user1083320

Say I have this:

说我有这个:

 <div class='container'>
      <img src='image1' id='1' />
      <img src='image2' id='2' />
      ...
 </div>
 <div class='container'>
 </div>

Now, I when I click on the container, I want to get the id of the image inside it. If the container contains no image, it should pop up an error saying no images in the container. Otherwise, I would like to get a list of all the ids of the images inside.

现在,当我单击容器时,我想获取其中图像的 id。如果容器不包含图像,它应该弹出一个错误,说容器中没有图像。否则,我想获取其中所有图像 ID 的列表。

Using jQuery, I have this:

使用 jQuery,我有这个:

 $('.container').click(function()
 {
      var images = $(this).find('img');
      if( images[0] == null ) { //no image found }
      else
      {
           // No idea what to do here :P
      }
 }

could someone please help me out here (I mean inside the else{} statement)? Thanks :)

有人可以在这里帮助我吗(我的意思是在 else{} 语句中)?谢谢 :)

回答by Purag

$(document).on("click", ".container", function(){
    var img = $(this).find("img"), // select images inside .container
        len = img.length; // check if they exist
    if( len > 0 ){
        // images found, get id
        var attrID = img.first().attr("id"); // get id of first image
    } else {
        // images not found
    }
});

Example.

例子

To get an array of the ids of all the images in the container:

要获取id容器中所有图像的s数组:

var arr = []; // create array
if( len > 0 ){
    // images found, get id
    img.each(function(){ // run this for each image
        arr.push( $(this).attr("id") ); // push each image's id to the array
    });
} else {
    // images not found
}

Example.

例子

And of course, what kind of a person would I be if I didn't give you an example with pure JS:

当然,如果我不给你举个纯 JS 的例子,我会是一个什么样的人:

var elems = [].slice.call( document.getElementsByClassName("container") );
elems.forEach( function( elem ){
    elem.onclick = function(){
        var arr = [],
            imgs = [].slice.call( elem.getElementsByTagName("img") );
        if(imgs.length){
            imgs.forEach( function( img ){
                var attrID = img.id;
                arr.push(attrID);
            });
            alert(arr);
        } else {
            alert("No images found.");
        }
    };
});

Example. A bit more complex, and I still recommend to use jQuery since it clears up all the cross browser mouse event madness.

例子。有点复杂,我仍然建议使用 jQuery,因为它清除了所有跨浏览器鼠标事件的疯狂。

回答by Ehtesham

    var images = $(this).find('img');
    if(images.length === 0) {
        alert('no images found');
    }
    else {
        var ids = new Array;
        images.each(function(){
           ids.push($(this).attr('id'));
        });
        //ids now contains all the ids of img elements
        console.log(ids);
    }

回答by dotnetstep

 $('.container').click(function() 
 {
 var images = $('img',this);
 if( $(images).length == 0 ) { 
        // No Image
    } 
    else       {   
        var ids = '';
        $(images).each(function(){
            ids = $(this).attr('id) + ",";
        });
        alert(ids);
    }  
}