我想让“this”引用实际触发事件的元素:
<div class="input-group">
<span class="input-group-addon header-text" id="action-header-text">Action</span>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="action-dropdown" data-toggle="dropdown" aria-expanded="true" style="min-width:250px;">
<span class=" caret">
</span>
</button>
<ul id="action-menu" class="dropdown-menu" role="menu"></ul>
</div>
</div>
填写Ajax请求:
function UpdateActionDropdown() {
$.ajax({
url: 'FrontEnd/Action',
type: 'POST',
dataType: 'json',
data: {
lid: document.getElementById('selected-language-id').value
},
success: function (data) {
document.getElementById('action-dropdown').firstChild.data = data.UnSelectable[0].ActionTrailer.DescriptionText;
$('#action-menu').html(null);
for (var i = 0; i < data.UnSelectable.length; i++) {
$('#action-menu').append("<li role='presentation' class='disabled'><a role='menuitem' tabindex='-1'>" + data.UnSelectable[i].ActionTrailer.DescriptionText + "</a></li>")
}
$('#action-menu').append("<li role='presentation' class='divider'></li>");
for (var i = 0; i < data.Selectable.length; i++) {
$('#action-menu').append("<li role='presentation'>" +
"<a role='menuitem' tabindex='-1' text='" + data.Selectable[i].DescriptionText + "' value='" + data.Selectable[i].ActionTrailer.ID + "'\" href='#'>" + data.Selectable[i].ActionTrailer.DescriptionText + "</a></li>")
}
}
});
}
全球聆听者:
$('.dropdown').on('click', '#action-menu li', function(){
// Inside here I want to access the li-element which got clicked.
});
我认为onclick Handler中的“this”会引用文档(或窗口)本身 - 是否可以引用实际的事件触发元素?
提前致谢!
答案 0 :(得分:10)
当你处于回调函数时,使用$(this)
DOM
(在jQuery的上下文中)元素
$('.dropdown').on('click', '#action-menu li', function(){
$(this)// It will be the li element clicked
});
请参阅jQuery: What's the difference between '$(this)' and 'this'?和https://remysharp.com/2007/04/12/jquerys-this-demystified