我有一个包含动态生成表单的模态。它是通过ajax调用加载的:
$(function() {
$('[data-toggle="modal"]').click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
if (href.indexOf('#') == 0) {
$(href).modal('open');
} else {
$.get(href, function(data) {
$('<div class="modal fade" id="modalR" tabindex="-1" role="dialog" aria-labelledby="modalR" aria-hidden="true">' + data + '</div>').modal();
});
}
});
});
在这个加载的表单中,我有一个div,我需要根据选择的表单字段隐藏/显示。我一直在使用以下代码,如果它已经在文件中,它可以正常工作。但是,当我将它添加到动态加载的模态形式时(模态中并不总是需要它),它不会执行。
$(function() {
$('#location').hide();
$("#type").change(function() {
if (this.value == '12') {
$('#location').show();
} else {
$('#location').hide();
}
});
});
任何提示?
答案 0 :(得分:0)
可能是因为当块已经存在于文件中时,jQuery会检测到它并绑定事件。但是当你通过ajax加载它时,就在绑定之后,所以新的块不会附加任何事件。因此,请在将其放在页面上后将其绑定。我的意思是,像这样:
$.get(href, function(data) {
$('<div class="modal fade" id="modalR" tabindex="-1" role="dialog" aria-labelledby="modalR" aria-hidden="true">' + data + '</div>').modal();
$('#location').hide();
$("#type").change(function() {
if (this.value == '12') {
$('#location').show();
} else {
$('#location').hide();
}
});
});