在 JavaScript 中使用 this.id?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13754532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using this.id with JavaScript?
提问by ZAX
I am passing a DOM object after an onclick event occurs and I need to know the id of the element I've passed from the html. I've read about the this.idthat exists in JavaScript but I cannot seem to utilize it correctly.
我在 onclick 事件发生后传递一个 DOM 对象,我需要知道我从 html 传递的元素的 id。我已经阅读了this.idJavaScript 中存在的 ,但我似乎无法正确利用它。
Here is my code in the function:
这是我在函数中的代码:
function clickFunction() {
$(".tictactoe").on('click', function() {
$(this).text("X");
if (this.id == "upleft") {
$('#upright').text("yes");
}
});
}
$(document).ready(function() {
$('#playagain').hide();
$('.tictactoe').on("click");
clickFunction();
});
So I thought that my quick test, if successful, would present the word yes in the grid of a tic tac to bar in the upper right corner when I clicked the position on the left.
所以我认为我的快速测试,如果成功,当我单击左侧的位置时,会在 tic tac 的网格中显示单词 yes 到右上角的栏。
Perhaps there is something wrong with my comparison?
也许我的比较有问题?
this.id == "upright"
The X's show up, indicating the rest of the code works, so it must be the comparison. Let me know your thoughts.
X 出现,表明其余代码有效,所以它必须是比较。让我知道你的想法。
回答by KingKongFrog
Pass the clickFunction in the click handler. Then remove the unnecessary click handler in the function.
在单击处理程序中传递 clickFunction。然后删除函数中不必要的点击处理程序。
$(document).ready(function(){
$('#playagain').hide();
$('.tictactoe td').on("click", clickFunction); //Added td click handler
});
function clickFunction()
{
$(this).text("X");
if(this.id == "upleft")
{
$('#upright').text("yes");
}
}
回答by user1884047
What happens if you used the following instead:
如果您改用以下内容,会发生什么情况:
$(this).attr('id') == "upright"

