[英]trying to get this jquery code working in my rails app, function not being called
我有一些代碼可以很好地用作html和js文檔。 可以從html文檔正確調用js腳本文件中的函數。 但是,當我將相同的代碼傳輸到我的軌道時,不會調用該函數。 如果有人可以提供一些建議,那將很棒。
我的application.js文件中有//= require autocomplete
,並且控制台中沒有任何錯誤。 我從application.html.erb生成的頁面是:
<div data-role="page" id="myPage">
<header data-role="header">
<h1>remote data</h1>
</header>
<div data-role="content">
<h3>Cities worldwide</h3>
<p>After you enter <strong>at least three characters</strong> the autocomplete function will show all possible matches.</p>
<ul id="autocomplete" data-role="listview" data-inset="true" data-filter="true" data-filter-placeholder="Find a city..." data-filter-theme="a"></ul>
<script>
console.log("test1");
$("#myPage").bind("pageshow", function(e) {
console.log("test2");
initialize_autocomplete();
});
</script>
</div>
<footer data-role="footer">
</footer>
</div>
我在控制台中看到“ test1”,但沒有出現“ test2”。 autocomplete.js中的test3和test4也不行。 我的autocomplete.js是:
function initialize_autocomplete() {
console.log("test3");
$( "#autocomplete" ).on( "filterablebeforefilter", function ( e, data ) {
console.log("test4");
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
if ( value && value.length > 2 ) {
$ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
$ul.listview( "refresh" );
$.ajax({
url: "http://gd.geobytes.com/AutoCompleteCity",
dataType: "jsonp",
crossDomain: true,
data: {
q: $input.val()
}
})
.then( function ( response ) {
$.each( response, function ( i, val ) {
html += "<li>" + val + "</li>";
});
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
});
}
});
}
謝謝你的幫助。
在我的application.html.erb中,順序為:
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
我將其更改為:
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
現在可以了。 那是正常的行為嗎? 我已經閱讀了一些有關javascript_include_tag的內容,但是如果有人可以用外行的術語表達,我將不勝感激。
嘗試使用以下代碼包裝代碼:
$(document).ready(function () {
// your functions defined here
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.