加载函数加载页面但不能对数据执行任何操作
So I load this:
所以我加载这个:
$('#categories').load("/Category/GetCats");
from this controller
来自这个控制器
public ActionResult GetCats()
{
var model = db.Cats
.Where(c => c.user_id == 5);
//var query = from c in db.Cats where c.user_id == 4 orderby c.catId select c;
//var i = query.Count();
//var results = query;
return PartialView("_PartialGetCats", model);
}
to render this view
渲染此视图
@foreach (var item in Model)
{
<tr>
<td data-id="@item.catId">@item.item_name</td>
</tr>
}
The categories show but this function
类别显示但是这个功能
$('#categories tr').on("click", function () {
var requestpage = "/Item/Partial?id=" + $(this).data("id");
alert(requestpage);
$.get(requestpage, function (result) {
$("#results").html(result);
});
or any other jquery functions do not recognize the $('#categories tr)
. It will however recognize $('#categories')
. I tested by removing the load()
and hardocding this
或任何其他jquery函数不识别$('#categages tr)。然而,它将识别$('#categories')。我通过删除load()和hardocding测试
$('#categories').html('<tr data-id="5"><td>new data</td></tr>');
and it works. Whats going on?
它的工作原理。这是怎么回事?
EDIT: full Index.cshtml view
编辑:完整的Index.cshtml视图
@{
ViewBag.Title = "Home Page";
}
<div id="categories">
</div>
<div id="results">
</div>
<div id="descrip">
</div>
2 个解决方案
#1
1
You either need to use event delegation or use the callback for jQuery .load()
.
您需要使用事件委派或使用jQuery .load()的回调。
jQuery .load()
callback method:
jQuery .load()回调方法:
Wait to wire up the click event until the HTML is in the DOM, this is why when you hardcode the HTML in via the .html()
function it works, because the on("click"
can find the elements to bind to. Instead do this:
等待点击事件连接,直到HTML在DOM中,这就是为什么当您通过.html()函数对HTML进行硬编码时,因为on(“click”可以找到要绑定的元素。做这个:
$('#categories').load("/Category/GetCats", function () {
$('#categories tr').on("click", function () {
var requestpage = "/Item/Partial?id=" + $(this).data("id");
alert(requestpage);
$.get(requestpage, function (result) {
$("#results").html(result);
});
});
});
Event delegation method:
事件委托方法:
This allows you to bind events to content that exists or may exist in the future, like this:
这允许您将事件绑定到将来存在或可能存在的内容,如下所示:
$('#categories').load("/Category/GetCats");
$("#categories").on("click", "tr", function(){
var requestpage = "/Item/Partial?id=" + $(this).data("id");
alert(requestpage);
$.get(requestpage, function (result) {
$("#results").html(result);
});
});
更多相关文章
- jquery不会对select/选项更改事件作出反应。
- 使用HTML5验证时如何绑定到提交事件?
- jquery自定义事件
- jQuery学习笔记- focus和blur事件妙用
- 具有嵌套元素的jQuery悬停事件
- 用jquery 绑定一个按钮click事件后,第一次点击后,一切正常,第二次点
- jQuery Sortable - 事件被调用太多次了
- Jquery注册服务器控件事件与判断控件的值
- 有关下拉框jquery里的change事件无法触发的问题