1
我一直在用一個簡單的JQuery事件處理程序摔跤數小時。 當頁面加載時,我的事件處理程序觸發一次,並且不會再次發生事件或與選擇框交互。 延遲時,警報(當我有一個)顯示第一個選擇選項。如果不是,則警報爲空。jQuery事件觸發一次,然後再也不會再發生
我想要的是從AJAX加載選擇框並讓用戶選擇觸發另一個AJAX調用。
HTML:
<select id="connection" name="Connection"></select>
<div id="testme" style="background: #CCC; width:100%; height:50px;position:relative;color:red">testing</div>
的Javascript:
$(document).ready(function() {
// Event handler. Tried as a separate function and as a parameter to $.on(...)
function connectionSelected() {
var str = $('#connection option:selected').text();
alert(str);
$("#testme").text(str);
}
var $connectionSelect = $('#connection');
//$connectionSelect.selectmenu(); // Tried enabling/disabling
// Tried this and all JS code inside and outside of $(document).ready(...)
$.when(
$.ajax({
dataType: "JSON",
url: '@Url.Content("~/API/ConnectionHint")', // The AJAX call (using ASP Razor) works fine
success: function(data) {
// This function is always called and works
var items = [];
$.each(data, function(key, val) {
items.push("<option value='" + key + "'>" + val + "</option>");
});
$connectionSelect.append(items.join(""));
// Tried setting up the event handler here
},
error: function() {
$connectionSelect.html('<option id="-1">none available</option>');
}
})
).then(function() {
//$("#connection option").blur(connectionSelected()).change();
$("#connection").on("change", connectionSelected());
});
});
試了幾十事件處理程序的變化,幾個事件,內部和deferred.done的外deferred.then等..例如:
$connectionSelect.selectmenu({
change: function (event, data) {
$('#connection').change(function() {
var str = "";
$('#connection').each(function() {
str += $(this).text() + "<br>";
});
$("#testme").text(str);
});
}
});
我平時寫後端代碼,而且只使用jQuery的部分熟悉不過了, 這真讓我抓狂。我在SO和其他地方看過超過30個相關的問題,例如
- Jquery event fires once
- Jquery .change() function not working with dynamically populated SELECT list
- http://jqueryui.com/selectmenu/#product-selection
任何想法讚賞。
'號'方式。有趣的部分是'()'在我的「嘗試隨機廢話」階段的故障排除期間是十幾種變化之一,但缺少無關'()'的變體有一個單獨的,無關的問題,我顯然固定在同時。不確定是笑還是哭。謝謝! – 2014-12-05 01:21:47
您必須始終通過JavaScript中的引用來傳遞迴調函數。記住這一點 :) – 2014-12-05 03:07:44