假设我有这样的代码,使用动态创建的元素:
$("#content").on("click", "img.MoveUpProposal", {
order: $(this).attr("order"),
elemId: "",
filterId: "",
direction: "UP",
targetToUpdate: "#proposalsOfReunionTable",
urlActionMethod: "MoveProposalOfCategory",
queryString: "?type=proposalsList"
}, ChangeOrder);
动态创建的元素:
<img src="~/Content/Images/enable_up_arrow.png" data-order="@item.SortOrder" data-elemid="@item.Id" class="MoveUpProposal" alt="UP" style="cursor:pointer;">
我如何访问这些属性?因为$(this).attr("order")
不起作用。什么是正确的方法?
这是我打电话的方法:
var ChangeOrder = function (order, elemId, filterId, direction,targetToUpdate, urlActionMethod, queryString) {
var options = {
url: '../'+urlActionMethod,
type: 'POST',
data: JSON.stringify({ order: order, elemId: elemId, filterId: filterId, direction: direction }),
contentType: "application/json",
}
$.ajax(options).done(function (result/* , textStatus, jqXHR */) {
if (result != null && result.success) {
var options2 = {
url: urlQuery = queryString,
data: "",
type: "get"
}
GetPartialViewUpdated(options2, targetToUpdate);
return true;
}
else { alert(result.responseText); }
});
return false;
}
答案 0 :(得分:1)
应该是$(this).attr("data-order")
,但是它不起作用,因为this
引用window
对象而不是触发事件的元素。
您需要在事件处理程序方法中访问它,并使用.data()
访问data-*
前缀属性。
$("#content").on("click", "img.MoveUpProposal", {
elemId: "",
filterId: "",
direction: "UP",
targetToUpdate: "#proposalsOfReunionTable",
urlActionMethod: "MoveProposalOfCategory",
queryString: "?type=proposalsList"
}, function(event){
var order = $(this).data("order");
ChangeOrder.call(this, event, $(this).data("order"), $(this).data("elemId"), event.data.filterId, event.data.direction,event.data.targetToUpdate, event.data.urlActionMethod, event.data.queryString);
});