首页 > 解决方案 > Javascript如何查看“$this”是否包含某个ID

问题描述

我想检查用户在网页中点击的对象是否包含某个 id。

我试过 .includes、.contains、.hasOwnProperty('val') 和其他几个,但没有运气。

如果对象包含#demo-id-name,那么它应该触发它下面的代码。

所以我的代码中有这个,我想这样做,如果用户首先点击它

标签,我想使用 javascript 检查单击的对象是否具有“#demo-id-name”。

jQuery(document).ready(function($) {
  "use strict";
  $(".demo-class").on("click",
    function(event) {
      var $this = $(this);
      if ($this.hasAttribute('#demo-id-name')) {

        /// redacted for brevity etc etc
        clickSpark.fireParticles($(this));
      }
    }):
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<p class="demo-class" id="demo-id-name">something </p>
<p class="demo-class">something ELSE </p>

标签: javascriptthis

解决方案


您可以使用.matches来检查元素是否与特定选择器匹配,无需先转换thisjQuery集合:

$(".demo-class").on("click", function() {
  if (this.matches('#demo-id-name')) console.log('match');
  else console.log('no match');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="demo-class" id="demo-id-name">something </p>
<p class="demo-class">something ELSE </p>

它不是必需的,但如果您确实想先包装thisjQuery,您可以使用以下is方法:

$(".demo-class").on("click", function() {
  if ($(this).is('#demo-id-name')) console.log('match');
  else console.log('no match');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="demo-class" id="demo-id-name">something </p>
<p class="demo-class">something ELSE </p>


推荐阅读