如何查找被点击的元素的ID

时间:2017-11-12 13:20:42

标签: javascript jquery html

我拥有class table row个,当点击其中一个时,会激活jQuery中的function捕获id被点击的element。我已经看过几篇关于如何做到这一点的帖子(即Getting the ID of the element that fired an eventJavaScript - onClick to get the ID of the clicked button),但没有一篇对我有用。

所以,我认为这样可行:

$(".yourStockTabs").click(function() {
    if (sellStockClicked === true) {
        var ids = $(this).attr("id");
        alert(ids);
    }
});

但事实并非如此。 sellStockClicked === true部分是检查器,以确保先前已点击过button。我一开始可能认为attribute的代码不正确或者variable不是真的,但我发现这两种情况都不是因为我删除了{{1} } if并注释了function部分并且只有id部分,但它仍然没有。

以下是完整代码:

alert

3 个答案:

答案 0 :(得分:2)

问题是您的变量sellStockClicked是在函数内声明的。

尝试在外部删除此变量声明:

var sellStockClicked ;
$("#sellStockButton").click(function() {
    sellStockClicked = true;
    alert("Please click on the row of the stock that you would like to sell.\n\nWhen you are finished, click this button again.");
    $(".yourStockTabs").css("background", "#E50000");
    $(".yourStockTabs").css("cursor", "pointer");
});
$(".yourStockTabs").click(function() {
    if (sellStockClicked === true) {
        var ids = $(this).attr("id");
        alert(ids);
    }
});
$("#sellStockButton").click(function() {
    if (sellStockClicked === true) {
       var sellStockClicked = false; 
    }
});

答案 1 :(得分:1)

香草



window.addEventListener("DOMContentLoaded", () => {
const e = document.body;
e.addEventListener("click" , e => {
console.log(e.target.id);
});
});

<input type="text" placeholder="clickme" id="itsmiId">
<input type="text" placeholder="clickme" id="wowclickme">
&#13;
&#13;
&#13;

答案 2 :(得分:0)

也许你在找这个:

var sellStockClicked = true;
var ids = [];

$("#sellStockButton").click(function() {
  alert("Please click on the row of the stock that you would like to sell.\n\nWhen you are finished, click this button again.");
  $(".yourStockTabs").css("background", "#E50000");
  $(".yourStockTabs").css("cursor", "pointer");
});
$(".yourStockTabs").click(function() {
  if (sellStockClicked === true) {
    ids.push($(this).attr("id"));
    alert(ids);
  }
});
$("#sellStockButton").click(function() {
  if (sellStockClicked === true) {
    sellStockClicked = false; 
  }
});