我需要通过点击获取元素的id
。
我尝试编写这个函数
$('.not-filled-button').click(function() {
statusFilter();
});
function statusFilter() {
// var $rows = $('#table tr');
alert($(this).get(0).id);
}
但是当我单击按钮时,它在警报中显示未定义
如果我这样写
$('.not-filled-button').click(function() {
//statusFilter();
alert($(this).get(0).id);
});
一切都好
如何使其在 1 种变体中工作?
最佳答案
您可以使用call或apply在这种情况下将上下文应用于所调用的函数。与此类似:
$('.not-filled-button').click(function() {
statusFilter.apply(this);
});
function statusFilter() {
// var $rows = $('#table tr');
alert(this.id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="someButton" class="not-filled-button">click me</button>
或者,您可以将元素作为参数传递,类似于:
$('.not-filled-button').click(function() {
statusFilter(this);
});
function statusFilter(element) {
// var $rows = $('#table tr');
alert(element.id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="someButton" class="not-filled-button">click me</button>
或者,正如评论中提到的,如果单击时您将调用的是 statusFilter
,则可以直接分配方法引用,类似于:
$('.not-filled-button').click(statusFilter);
function statusFilter() {
// var $rows = $('#table tr');
alert(this.id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="someButton" class="not-filled-button">click me</button>
关于javascript - 通过点击获取元素的id(JS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47750498/