2015-12-21 64 views
-1

我有一堆動態創建的錨標籤。我基本上想調用一個函數,並使用jQuery的slideDown在該錨標籤下顯示該執行函數的內容。每<a>標籤與id="id"和每個<a>標籤有一個<div id="slidedown">一下滑一下標籤就不滑動

我正在使用jquery.slideto.min.js。

下面的代碼甚至不會滑落。

$(function() { 
    $.ajax({ 
     dataType: 'json' 
     url: '/lists', 
     success: function (data) { 
      if (data != null) { 
       var html = '<ul>'; 
       $.each(data.apis, function (i, item) { 
        html += '<li class="res">'; 
        html += '<div class="hed"><h2><a id="id" href="/api/' + item + '.json">' + item + '</a></h2></div><div id="slidedown"></div>'; 
        html += '</li>'; 
       }); 
       html += '</ul>'; 
       $('#exDiv').empty(); 
       $('#exDiv').append(html); 
      } 
     }, 
     error: function() { 
      alert('Error'); 
     }, 
     contentType: 'application/json' 
    }); 

    $(document).on('click','#id', function(e) { 

     e.preventDefault(); 
     var link = this.href; 
     $('#slidedown').slideto(); 
    }); 
}); 

我看到Uncaught TypeError: Cannot read property 'version' of undefined我的控制檯上一次我點擊任何<a>標籤。

+0

這將有助於看到您的HTML,但它聽起來像你有幾個問題。首先是'#a'和'#slideown'元素將被複制,這是無效的,因爲'id'屬性在文檔中必須是唯一的。改爲使用班級。其次,你需要遍歷'this'的引用中的DOM來找到相鄰的'.slidedown'元素並在其上調用'slideto()'。 –

+0

@RoryMcCrossan請檢查,更新 – fscore

+0

謝謝 - 我給你添加了一個答案 –

回答

0

不知道這會解決這個問題,但$('slidedown')是不是一個有效的選擇,應該是$('#slidedown'),因爲你有div標識符爲slidedown<div id="slidedown">

0

您遇到的主要問題是您生成的重複id屬性無效。改爲將它們改爲類。然後,您可以遍歷click()處理程序中的DOM,以使用next()找到相關的.slidedown元素。試試這個:

$.ajax({ 
    dataType: 'json' 
    url: '/lists', 
    success: function (data) { 
     if (data != null) { 
      var html = '<ul>'; 
      $.each(data.apis, function (i, item) { 
       html += '<li class="res">'; 
       html += '<div class="hed"><h2><a class="id" href="/api/' + item + '.json">' + item + '</a></h2></div><div class="slidedown"></div>'; 
       html += '</li>'; 
      }); 
      html += '</ul>'; 
      $('#exDiv').empty().append(html); 
     } 
    }, 
    error: function() { 
     alert('Error'); 
    }, 
    contentType: 'application/json' 
}); 

$(document).on('click','.id', function(e) { 
    e.preventDefault(); 
    var link = this.href; // you can remove this if it's not used. 
    $(this).next('.slidedown').slideto(); 
}); 
+0

我嘗試了上面的代碼更改,但仍然無效 – fscore