我拥有class
table
row
个,当点击其中一个时,会激活jQuery中的function
捕获id
被点击的element
。我已经看过几篇关于如何做到这一点的帖子(即Getting the ID of the element that fired an event或JavaScript - 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
答案 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;
答案 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;
}
});