我有mvc4项目。我正在使用bootstrap 3.1.1。我在bootstrap模型中包含局部视图。我在局部有一个按钮,我想点击那个按钮做一些自定义逻辑。部分负荷,我可以看到模态。但是,部分视图中存在的按钮上的click事件永远不会被调用。
任何帮助将不胜感激。我正在使用Jquery 1.11。
控制器
public ActionResult Index()
{
return View();
}
public ActionResult Login()
{
return PartialView("Partial1");
}
部分视图
<div class="modal-body">
<div class="panel panel-default">
<div class="panel-body">
<button class="btn btn-inverse" type="submit" id="cmdUpdatePhone">Update & Continue</button>
<button class="btn btn-inverse" type="submit" id="cmdContine">Continue</button>
</div>
</div>
</div>
Index.cshtml
@{
ViewBag.Title = "Index";
}
<div class="container">
<h2>Index</h2>
<div class="modal" id="edit-phone" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div id="edit-phone-container"></div>
</div>
</div>
</div>
<button type="button" id="cmdTest">Test</button>
</div>
脚本
@section Scripts {
<script type="text/javascript">
$(function () {
$(document).ready(function () {
// This will work because we are listening on the 'document',
// for a click on an element with an ID of #test-element
$('document').on("click", '#cmdUpdatePhone', function (e) {
alert("click bound to document listening for #test-element");
});
});
$('#cmdTest').click(function (e) {
e.preventDefault();
$.ajax({
url: '@Url.Action("Login")',
data: '',
success: function (response) {
$('#edit-phone-container').html(response);
$('#edit-phone').modal({
backdrop: 'static',
show: true
});
},
error: function (data) {
console.log(data);
},
type: 'POST',
contentType: 'application/json, charset=utf-8'
});
});
});
</script>
}
答案 0 :(得分:1)
这是错误:
$('document').on("click", '#cmdUpdatePhone', function (e) {
alert("click bound to document listening for #test-element");
});
您不需要在文档中使用引号,因为文档不是html标记,请执行以下操作:
$(document).on("click", "#cmdUpdatePhone", function (e) {
alert("click bound to document listening for #test-element");
});
或者你可以这样做:
$('body').on("click", "#cmdUpdatePhone", function (e) {
alert("click bound to document listening for #test-element");
});
答案 1 :(得分:0)
由于在页面加载后动态加载按钮,您需要将click事件与文档绑定。变化
$('#cmdTest').click(function (e) {
到
$(document).on('click', '#cmdTest', function (e) {...