检查点击的 div id 是否与变量匹配

Check if the clicked div id matches with variable

我是一名编码新手,正在寻找一种方法来检查 jQuery 某个变量的名称是否对应于 div 的 ID,如果是,则触发一些代码。不幸的是,我的语法有些问题,我不知道是什么。

举个简单的例子,我想点击一个div并将div的ID存储为一个变量,如果我再次点击它,变量就会被清除。由于代码的其余部分,无法简单地分配另一个布尔变量,我需要 ID-check-thingy 或类似的东西。

这是我目前得到的:

<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
        }
    });
});

您的代码中有 2 个问题:

1) 此处的 if 比较不需要额外的 ID 选择器。 .attr("id") returns 元素的 ID,而不是它的选择器。

2) 您不需要在 if 和 else 条件中重新声明变量。由于在这些条件下重新定义变量,将其范围限制在特定条件内。

此外,您应该尽量减少为目标元素重新创建 jquery 对象。创建一次然后再次使用它始终是一个好习惯:

var $this = $(this);
var clickedElement;
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
        clickedElement = null;     // reset the variable
} else {
        clickedElement = $this.attr("id");     // the div has been clicked, assign its ID to the variable
}

您可以直接将您的变量与 this.id

进行比较
if(this.id == clickedElement)

但是我建议您使用 .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>