我想检查用户在网页中点击的对象是否包含某个id。
我试过 .includes、.contains、.hasOwnProperty('val') 和其他几个,但没有成功。
如果对象包含#demo-id-name,那么它应该触发它下面的代码。
所以我的代码中有这个,我想这样做,如果用户点击第一个
标签,我想使用 javascript 检查点击的对象是否有“#演示 ID 名称”。
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>
最佳答案
您可以使用 .matches
来检查元素是否与特定选择器匹配,无需将 this
转换为 jQuery
集合第一:
$(".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>
这不是必需的,但如果您确实想先在 jQuery 中包装 this
,您可以使用 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>
关于Javascript 如何查看 "$this"是否包含某个 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52771317/