2015-06-21 71 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!)