您好我有一个显示jquery datepicker的页面,并根据datepicker提取并显示自定义表单:
<div id="datepicker"></div>
<script type="application/javascript">
function fetch_form (date_string, inst) {
var date = $('#datepicker').datepicker('getDate');
var date_list = [date.getFullYear(), date.getMonth() + 1, date.getDate()];
var url = "/luncher/by_date/" + date_list.join("/");
$.ajax({
url: url,
cache: false,
success: function(html){
$("#form-container").html(html);
}
});
ajax_form();
}
function ajax_form () {
$("#food_form").ready(function(){
$("#food_form").submit(function(e){
alert(e);
});
});
}
$('#datepicker').datepicker({
firstDay: 1,
onSelect: fetch_form,
});
now = new Date();
fetch_form(now);
</script>
</div>
<div class="span6" id="form-container">
</div>
问题是我需要为获取的表单设置自定义.submit函数,我在ajax_form函数中尝试过,但是表单忽略了我的自定义并且表单以正常方式提交。
以下是提取的示例表单:
<h1>Dishes for Dec. 15, 2011</h1>
<form id="food_form" action="/luncher/by_date/2011/12/15" method="post">
<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='9ba228bab1a61b993eba4180f2a2237e' /></div>
<table>
<tr><th></th><th>Dish:</th><th>Enjoyed?</th><th>More often?</th></tr>
<tr><td>Lunch</td><td><select name="lunch" id="id_lunch">
<option value="55">Vinná klobáska s bramborovou kaší</option>
<option value="56">Filety s koprovou omáčkou</option>
<option value="57">Dukátové buchtičky</option>
</select></td><td><input type="checkbox" name="lunch_taste" id="id_lunch_taste" /></td><td><input type="checkbox" name="lunch_preference" id="id_lunch_preference" /></td></tr>
<tr><td>Soup</td><td><select name="soup" id="id_soup">
<option value="53">Zeleninový vývar</option>
<option value="54">Bramborová</option>
</select></td><td><input type="checkbox" name="soup_taste" id="id_soup_taste" /></td><td><input type="checkbox" name="soup_preference" id="id_soup_preference" /></td></tr>
<tr><td>Dinner</td><td><select name="dinner" id="id_dinner">
<option value="58">Kuřecí nudličky gyros s tzatzikami</option>
<option value="59">Sýrové těstoviny</option>
</select></td><td><input type="checkbox" name="dinner_taste" id="id_dinner_taste" /></td><td><input type="checkbox" name="dinner_preference" id="id_dinner_preference" /></td></tr>
</table>
感谢您的帮助!
答案 0 :(得分:2)
$(document).on('submit', '#food_form', function(e){
alert(e);
e.preventDefault();
});
答案 1 :(得分:1)
$('#form-container').on('submit', '#food_form', function () {
//custom code here
});
像这样使用.on()
类似于我们的.delegate()
:
将处理程序附加到与现在或将来匹配选择器的所有元素的事件中, 基于一组特定的根元素
来源:http://api.jquery.com/delegate/
另一种解决方案是在将表单插入DOM时附加事件处理程序:
$.ajax({
url: url,
cache: false,
success: function(html){
$("#form-container").html(html);
$('#food_form').on('submit', function () {
//custom code here
});
}
});
像这样使用.on()
类似于.bind()
,其中在调用时元素必须存在于DOM中。