【问题标题】:How to get img inside a particular div using JQuery如何使用 JQuery 在特定 div 中获取 img
【发布时间】:2015-11-07 20:59:38
【问题描述】:

我必须获取特定 div 中的所有图像标签 ID。我怎样才能使用 JQuery 获得它?

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:
    var arraysOfIds = $('#particularDivId img').map(function(){
                           return this.id;
                       }).get();
    
    // arraysOfIds has now all the id's, access it as arraysOfIds[0], arraysOfIds[1]....  
    

    【讨论】:

    • 啊,酷。我通过 .map() 功能学到了一些新东西。但是,查看文档,为什么最后需要 .get() 调用。我只是在没有它的情况下尝试了您的代码,它运行良好。想要学习的新手。
    【解决方案2】:

    粗略猜测,但请尝试:

    var imgIds = new Array();
    
    $("div#divID img").each(function(){
        imgIds.push($(this).attr('id'));
    });
    

    您没有给出div 的名称,但我使用divId 作为 div 的 id。只需根据您的需要进行更改即可。

    【讨论】:

    • 你应该使用数组,而不是字符串。
    【解决方案3】:

    使用子选择器。所以你说我想要 div #myDiv 的所有子 'img' 元素

    $("#myDiv > img").css("border", "3px double red");
    

    http://api.jquery.com/child-selector/

    【讨论】:

    • 我想让这个工作,当我替换 $('img').doStuff();与 $("#contents > img").doStuff();它不再做任何事情。我也试过单引号和 div#contents。
    • 我的解决方案是使用后代选择器而不是子选择器。 link
    • 这不会选择 div 的所有子 img 元素,而只会选择直接后代。
    【解决方案4】:
    function textOnly() {
                jQuery('#dvContent img').each(function () {
                    jQuery(this).css('display', 'none');
                });
            }
    

    【讨论】:

      猜你喜欢
      • 2011-01-09
      • 1970-01-01
      • 2020-09-05
      • 2018-07-13
      • 2013-04-16
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      • 2019-05-20
      相关资源
      最近更新 更多