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

时间:2016-12-15 13:42:48

标签: jquery variables if-statement variable-assignment

我是一个编码新手并且正在寻找一种方法来检查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 个答案:

答案 0 :(得分:1)

您可以直接将变量与<button onclick="doMath()">Click</button> <p id="output"></p>

进行比较
this.id

但我建议您使用.is()

if(this.id == clickedElement)

&#13;
&#13;
if($(this).is('#' + clickedElement))
&#13;
$(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
    }
  });
});
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您的代码中有2个问题:

1)如果在这里比较,你不需要额外的ID选择器。 .attr("id")返回元素的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
}
相关问题