我试图获取 DOM 树中被单击的元素,并且在我单击同一个元素的地方必须附加该属性,如果我再次单击同一个元素,它必须检查它是否存在已删除。
当前行为:当我单击一个元素时,我会在警报中获取该元素(p、div、选项等),但问题是当我添加属性时,它被添加到父 div 中。
更新:当 Ajax 发生时,属性将被删除。
JS:
$('#search-refine-bar').on('click', function(e) {
var eventNode = e.target.nodeName;
var refineChil = $('#search-refine-bar').children();
var refineHasAttr = $('refineChil').attr({
tabindex: "-1",
focus: "focus"
});
alert(eventNode)
if ($("#search-refine-bar").is('[focus]')) {
alert(eventNode + " ----- " + 'attribute exists should be removed');
$(this).removeAttr('tabindex focus style')
} else {
alert(eventNode + " ----- " + ' NO attribute exists...adding attribute');
$(this).attr({
tabindex: "-1",
focus: "focus"
}).css({
"border": "1px solid #f00"
});
}
});
感谢您的帮助:)
最佳答案
您需要从 e.target 添加/删除属性.
在事件处理程序内 this
引用处理程序的目标(在本例中为 #search-refine-bar
),但因为您需要单击的实际元素您可以使用 event 的 target
属性
$(e.target).removeAttr('tabindex focus style')
演示:Fiddle
关于javascript - 获取当前单击的元素并在 jquery 中添加属性不适用于子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25680347/