检查点击的div id是否与变量匹配 [英] Check if the clicked div id matches with variable
问题描述
我是一个编码新手并且正在寻找一种方法来检查jQuery某个变量的名称是否与div的ID相对应,如果是这样,则会触发一些代码。不幸的是,关于我的语法的一些东西是关闭的,我无法弄清楚是什么。
I'm a coding newbie and looking for a way to check in jQuery whether the name of a certain variable corresponds to the ID of a div, and if so fire some code. Unfortunately, something about my syntax is off, and I can't figure out what.
对于一个简单的例子,我想点击一个div并存储该ID的ID div作为变量,如果我再次单击它,变量将被清除。由于剩下的代码,简单地分配另一个布尔变量是不可能的,我需要ID-check-thingy或类似的东西。
For a simple example, I want to click a div and store the ID of the div as a variable, and if I click it again the variable gets cleared. Simply assigning another boolean variable is not possible due to the rest of the code, I require the ID-check-thingy or something similar.
这就是我所拥有的远:
<div class="testdiv" id="primary">Bananarama</div>
$(document).ready(function() {
$(".testdiv").click(function() {
if ($(this).attr("id") == "#" + clickedElement) {
// if the ID of the clicked div matches the variable, proceed. This is the part that doesn't seem to work
alert ("Victory"); // display alert so we know everything worked out
var clickedElement = null; // reset the variable
} else {
var clickedElement = $(this).attr("id"); // the div has been clicked, assign its ID to the variable
}
});
});
推荐答案
您可以直接将变量与<$ c进行比较$ c> this.id
if(this.id == clickedElement)
但我建议您使用 .is()
However I would recommend you to use .is()
if($(this).is('#' + clickedElement))
$(document).ready(function() {
var clickedElement;
$(".testdiv").click(function() {
if (this.id == clickedElement) {
// if the ID of the clicked div matches the variable, proceed. This is the part that doesn't seem to work
alert("Victory"); // display alert so we know everything worked out
clickedElement = null; // reset the variable
} else {
clickedElement = this.id; // the div has been clicked, assign its ID to the variable
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="testdiv" id="primary">Bananarama</div>
这篇关于检查点击的div id是否与变量匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!