我一直在与一个简单的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多个相关问题,例如
任何想法表示赞赏。
代替
$("#connection").on("change", connectionSelected());
尝试
$("#connection").on("change", connectionSelected);
请注意,在第二篇文章中,我通过引用传递了函数处理程序,而不是调用它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句