无法滚动到动态元素

时间:2015-05-21 03:32:57

标签: javascript jquery

嘿伙计们,我有一些问题滚动到一个动态创建的元素。您单击搜索按钮,AJAX会执行其操作并更新内容。我有一些代码来动态查找ID并滚动到它。我能够获取ID,但我无法滚动到它。到目前为止,我有代码:

to_Scroll = $(this).closest('tr').attr('id');
$('html, body').animate({
    scrollTop: $(to_Scroll).offset().top
}, 2000);

当我将它放在带有硬编码数据的控制台中时,这似乎有效。但是动态地做它不会产生结果而且没有错误。任何帮助将不胜感激

下面是一些代码,它在我动画和滚动到元素之前完成:

dateChange(blah, blah2, blah3);
to_Scroll = $(this).closest('tr').attr('id');
    $('html, body').animate({
        scrollTop: $(to_Scroll).offset().top
    }, 2000);

function dateChange(dateInput, nGuests, vName){
    var promises = [];
    var promise = $.ajax({
          url: "/blah.asp?blah="+blah+"&blah2="+blah2+"&blah3="+blah3,
          dataType:"html",
          success: function(data){
              table.html(data);
          }
        });
    promises.push(promise);

$.when.apply($, promises).done(function() {
    $( "#boatContent" ).removeClass( "loading" ); //Everything is done, remove loading gif
    //do other stuff
}

1 个答案:

答案 0 :(得分:3)

再次从attr使用ID你需要添加#

$(document).ready(function(){
    var to_Scroll = $(this).closest('tr').attr('id');
    $('html, body').animate({
        scrollTop: $( '#' + to_Scroll).offset().top
    }, 2000);
});