我试图将一个类添加到单击的元素。有多个具有唯一ID的元素,因此我“不知道”该元素的ID是什么。
我可以使用以下代码的修改版本来实现此目的吗?
jQuery:
$(document).ready(function () {
$(this).on('click', function () {
$(this).addClass('widget-selected');
});
});
编辑:
标记可以像这样:
<h1 id="textHolder1" contenteditable="true">Text to edit</h1>
最佳答案
我会尝试的..
$(document).ready(function () {
//this will attach the class to every target
$(document).on('click', function (event) {
$target = $(event.target);
$target.addClass('widget-selected');
});
})
或者如果您想检查某种
id
的使用 ...
if(event.target.id === "idname") { ... }
...