javascript - 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>
解决方案
您可以使用.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>
它不是必需的,但如果您确实想先包装this
jQuery,您可以使用以下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>
推荐阅读
- google-apps-script - google script 太慢了,有没有办法加快速度?
- ruby - 如何从部分 Rails 6 创建嵌套模型
- excel - vba excel我可以将sendkeys的睡眠设置为低于500(0.5秒)并且仍然可以顺利运行
- angular - 抽象类中的角度事件处理
- linux - 'sh'和'source'(和'.')执行shell脚本的区别
- python - 如何从 Tableau 仪表板中提取值
- javascript - 如何使函数的代码更可重用
- javascript - 有没有办法让我的不和谐机器人区分另一个不和谐机器人的成功和不成功命令?
- netlogo - 如何从输入框中读取包含海龟值的公式?
- amazon-dynamodb - 对 Amazon DynamoDB 中的多个属性进行 OR 查询