2015-06-21 52 views
1

我想为标签'li'添加一些细节,因此我将详细信息存储到标记'a'中。jQuery - func append,第一个出现两次

但它不好用。索引'0'出现两次。

相关代码。

<div class="frame"> 
     <ul> 
      <li> 
       <a class="thumb" href="#" />   
       <img title="EOC 450D Camera" src="image/picture1.jpg"/> 
       <a class= "descript" href="test1" /> 

      </li> 
      <li> 
       <a class="thumb" href="#"/> 
        <img title="A Set of Camera Lenses" src="image/picture2.jpg"/> 
       <a class = "descript" href="test2" /> 

      </li> 
      <li> 
       <a class="thumb" href="#"/> 
        <img title="Profession Camera" src="image/picture3.jpg"/> 
       <a class= "descript" href="test3" /> 
      </li> 
      <li> 
       <a class="thumb" href="#"> 
        <img title="EOC 2100D Camera" src="image/picture4.jpg"/> 
       </a> 
      </li> 
     </ul> 
    </div> 

jQuery的一部分:

$items.each(function(){ 
     var $this = $(this), 
      _href = $this.find('a').attr('href'), 
      _title = $this.find('img').attr('title'); 
     var _text = $this.find('.descript').attr('href'); 

     $this.append('<div class="ovrly">' + 
      '<h3>' + 
       '<a href="' + _href + '" alt="' + _title + '" title="' + _title + '">' + _title + '</a>' + 
      '</h3>' + '<br>' + _text + 
      '</div>').find('.ovrly').css('opacity', _opacity); 
    }); 

但效果是这样的。 the test1 has appeared twice!

谢谢!

回答

2

我相信浏览器正在与您的自动关闭<a ... />元素混淆。如果你把它们全部改为单独关闭</a>标签,那么它似乎工作正常。

也就是说,更改:

<a class="thumb" href="#" /> 

<a class="thumb" href="#"></a> 

等等。虽然可能每个<img>元素应该位于每个<li>的第一个锚点内,就像您对第四个元素所做的一样。

演示:http://jsfiddle.net/5jp0f3or/

(运行在Chrome的代码,我试图console.log($("a").length);,它显示13关闭所有的锚与</a>,并再次尝试登录它的预期7!)