2015-10-04 75 views
1

您可以請看看This Demo,讓我知道如何啓用從自動完成滾動到所選項目的div?添加滾動功能與UI自動完成

$(document).ready(function() { 
    $('#tags').on('change', function() { 
     $('#tagsname').html('You selected: ' + this.value); 
     $('html,body').animate({ 
       scrollTop: $("#"+ this.value).offset().top 
     }); 
    }).change(); 
    $('#tags').on('autocompleteselect', function (e, ui) { 
     $('#tagsname').html('You selected: ' + ui.item.value); 
    }); 
}); 

但我得到這個錯誤

Uncaught TypeError: Cannot read property 'top' of undefined

回答

-1

change事件不存在,所以你的代碼不會被觸發。你必須這樣做:

$(document).ready(function() { 
    $('#tags').on('autocompleteselect', function (e, ui) { 
     $('#tagsname').html('You selected: ' + ui.item.value); 
     $('html,body').animate({ 
       scrollTop: $("#"+ this.value).offset().top 
     }); 
    }); 
}); 

檢查this demo

+0

你是什麼意思'更改'不存在? OP將其應用於文本框而非選擇。如果它不存在,它不會觸發,因此OP不會得到錯誤。 – rism

+0

JavaScript編譯器在執行之前檢查所有代碼,分配變量並在執行前檢查變量或變量屬性是否存在。另一方面,'change'事件必須被初始化才能被觸發,這就是爲什麼你必須在'autocomplete'初始化中添加一個回調函數。這是一個可觀察的模式。 http://api.jqueryui.com/autocomplete/#event-change –

+0

不,事件會由於OP調用它而觸發。 '.change();' – rism

0

代碼在正確觸發時起作用。但是,只有在輸入與其中一個查找項目相匹配的值時才能正確觸發它。

按照Jquery documentation爲ID選擇:

For id selectors, jQuery uses the JavaScript function document.getElementById(), which is extremely efficient.

至於每MDN爲的document.getElementById參數

  • 元件是一個Element對象的引用或null如果與一個元件指定的ID不在文檔中。
  • id是一個區分大小寫表示正在查找的元素的唯一ID的字符串。

由於您的要素使用Proper Cased串IDS定義,因爲ID查找是大小寫敏感的,如果你的ASP元素進入asp它將返回null的查找。

隨後致電offset()null將返回undefined。由於undefined沒有財產top你得到你的錯誤消息:

Uncaught TypeError: Cannot read property 'top' of undefined

所以解決的辦法是你的IDS設置一些情況下,規範你的電話。例如,如果你使用較低的情況下,則:

$("#"+ this.value.toLower()).offset().top 

或者更好的做一些空的檢查等,以確保你確實有一個項目bfore你開始調用它的方法:

function getOffset(id){ 
    if (this.value) 
    { 
     var matches = $("#"+ this.value.toLower()); 
     if (matches.length){ 
     return matches.offset().top; 
     } 
    } 
    return 0; 
} 

scrollTop: getOffset(this.value);