【问题标题】:Using jquery, how can i find if an image exists with a certain attribute that is within a div?使用jquery,我怎样才能找到一个图像是否存在一个div中的某个属性?
【发布时间】:2013-11-30 05:17:14
【问题描述】:

如果我有以下 html:

<div id="container">
           <img personId="12" src"Joe.png" />
           <img personId="16" src"Scott.png" />
           <img personId="17" src"Bill.png" />
</div>

是否可以:

  1. 返回该容器 div 内的图像中存在的 personId 列表

  2. 有一个功能可以搜索图片列表中是否存在某个数字(看同一个属性)

我尝试使用 find() 但这似乎不起作用

【问题讨论】:

  • 只是一个流氓评论;尽量不要使用非标准的属性,你可以将“personId”改为“data-personid”并兼容html。

标签: jquery jquery-selectors selector


【解决方案1】:

要获取所有值,您可以使用.map() 方法:

var ids = $('#container img[personId]').map(function(){
   return this.getAttribute('personId');
}).get();

为了检查值的存在,您可以使用$.inArray() 实用函数。

if ( $.inArray(id, ids) > -1 )

【讨论】:

    【解决方案2】:

    在 jQuery 中使用 attr 函数:

    arr = [];
    $('#container')
      .children()
      .each(function () {
        arr.push($(this).attr('personId'));
      });
    

    【讨论】:

      【解决方案3】:

      使用 jquery attr() 方法..

      jQuery('img').each(function(){
          _IMG = jQuery(this);
          var pid = _IMG.attr('personId');
          console.log(pid);
      });
      

      对于搜索功能,我猜是这样的:

      jQuery(function($){
          var pidToSearchFor = 17;
          jQuery('img').each(function(index){
              _IMG = jQuery(this);
              var pid = _IMG.attr('personId');
      
              if(PERSONS.isSame(pid)) {
                  console.log("FOUND! IN IMAGE NO."+index)}
      
          });
      
      
      });
      
      var PERSONS = {
      toSearchFor = 17,
      isSame: function(pidIn) {
              _IMG = jQuery(this);
              if (toSearchFor == pidIn) {return true}
              else {return false}
      
      
      }
      

      }

      【讨论】:

        【解决方案4】:

        采用未定义的选择器

        function getPersonIdList()
        {
            var personIdList = new Array();
            var personIds = $("#container img[personId]").each(
                    function()
                    {
                        personIdList[personIdList.length] = $(this).attr("personId");
                    });
        
            return personIdList;
        }
        
        function isPersonIdExists(personId)
        {
            var personIds = $("#container img[personId='" + personId + "']");
            if (personIds.length > 0)
                return true;
        
            return false;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-10-15
          • 1970-01-01
          • 2021-10-25
          • 2020-04-21
          • 1970-01-01
          • 2014-06-10
          • 2016-09-11
          相关资源
          最近更新 更多