我有一个动态悬停,它根据隐藏元素是否存在而激活。我正在更新代码以合并动态创建的元素,但遇到了问题并且不知道如何选择父元素。
之前我使用了$(".infotip").parent().hover
,但已更新为:
$(document).on("mouseenter", ".parent-selector", function() {
$(this).find(".infotip").addClass("active");
});
$(document).on("mouseleave", ".parent-selector", function() {
$(this).find(".infotip").removeClass("active");
});
所以需要发生的是我需要 ".parent-selector"
表现得像 $(".infotip").parent()
最佳答案
由于内容是动态的,并且您提到在创建时无法将类添加到父级,因此我认为执行此操作的唯一方法是监视已添加的任何新元素,然后绑定(bind)您的事件。
此函数将定期查找任何带有 .infotip
的元素没有我们自定义的类 events_bound
属性已经。如果找到,它将添加该属性,然后将鼠标事件绑定(bind)到父级。我已经添加了一个 fiddle ,用动态内容来说明这一点。
//check for changes in the dom
setInterval(function() {
$('.infotip:not([events_bound])').each(function() {
//add attribute so that we don't re-bind to this element
$(this).attr('events_bound', true);
//now bind the events to the parent
$(this).parent().mouseenter(function() {
$(this).find(".infotip").addClass("active");
})
$(this).parent().mouseleave(function() {
$(this).find(".infotip").removeClass("active");
})
});
}, 500);
https://jsfiddle.net/ybrwv0c8/1/
当然,如果有关于父项的任何信息可识别,那么最好的方法是为您的 on
使用选择器。例如,如果有一个动态生成的 ID,其标准结构如 parent_13835723
,您可以执行部分属性选择器,例如 $('[id^=parent_]')
您也许还可以使用 jquery :has
像这样的伪选择器。但是,这会在所有后代中搜索某个元素,这可能无法正常工作,具体取决于 DOM 的结构。
$(document).on("mouseenter", ":has('.infotip')", function() {
$(this).children('.infotip').addClass("active");
});
$(document).on("mouseleave", ":has('.infotip')", function() {
$(this).children('.infotip').removeClass("active");
});
但是,根据此处的 jquery 文档 http://api.jquery.com/has-selector/ :
The expression
$( "div:has(p)" )
matches a<div>
if a<p>
exists anywhere among its descendants, not just as a direct child.Because :has() is a jQuery extension and not part of the CSS specification, queries using :has() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use
$( "your-pure-css-selector" ).has( selector/DOMElement )
instead.
我不确定 :has
是否或setInterval
方法会有更好的性能。
关于javascript - 如何使用选择器选择父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38207850/