有没有办法动态检测哪个元素在 JQuery 中触发事件?
Is there a way to dynamically detect which element is firing an event in JQuery?
我有一段代码,可以动态更新用户信息。与其说是代码异味,不如说是个大问题,但我不得不在当前代码中使用具有不同元素的相同代码!我想让这个函数多态化以便将来维护(想象一下如果页面上有 50 多个项目!)
我理想的解决方案看起来像这样(伪代码)
function (/* element firing the save event */, /* changed property on my MVC Model */) {
$('.ChangedElement').on('save', function (e, params) {
var Property = $("#ModelProperty").text().replace(" ", "");
$.ajax({
type: "POST",
url: "/Dealer/UpdateDealer",
data: {
UpdatedValue: params.newValue,
UpdatedPropertyName: Property
},
async: true,
success: function (result) {
alert(JSON.stringify(result));
}
});
});
};
我将不胜感激,因为我完全不知道从哪里开始。
$(this) 将指向调用事件的元素,因此使用属性方法获取元素的 id。
$(this).attr('id')
我有一段代码,可以动态更新用户信息。与其说是代码异味,不如说是个大问题,但我不得不在当前代码中使用具有不同元素的相同代码!我想让这个函数多态化以便将来维护(想象一下如果页面上有 50 多个项目!)
我理想的解决方案看起来像这样(伪代码)
function (/* element firing the save event */, /* changed property on my MVC Model */) {
$('.ChangedElement').on('save', function (e, params) {
var Property = $("#ModelProperty").text().replace(" ", "");
$.ajax({
type: "POST",
url: "/Dealer/UpdateDealer",
data: {
UpdatedValue: params.newValue,
UpdatedPropertyName: Property
},
async: true,
success: function (result) {
alert(JSON.stringify(result));
}
});
});
};
我将不胜感激,因为我完全不知道从哪里开始。
$(this) 将指向调用事件的元素,因此使用属性方法获取元素的 id。
$(this).attr('id')