javascript - 如何使用选择器选择父级

标签 javascript jquery

我有一个动态悬停,它根据隐藏元素是否存在而激活。我正在更新代码以合并动态创建的元素,但遇到了问题并且不知道如何选择父元素。

之前我使用了$(".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/

相关文章:

javascript - 如何检索 HTML "style"元素?

javascript - 如何在 ShieldUI Grid 中仅使选定的列可编辑?

javascript - 我在使用 setInterval 和类方法时遇到了很多麻烦

jquery - 使用 jQuery live 或 delegate 触发事件

java - Ajax中获取Action方法结果状态

javascript - jQuery:对列求和并将它们合并到一个单元格(用 SUM 结果替换它们)

javascript - 鼠标悬停动画奇怪的行为

javascript - 如何使用 Vue.js Firebase UID 删除用户

jQuery Ajax Post - 打印您刚刚在回调中发布的数据

jquery - 具有 CSS-toggle-effect 的响应式 DIV : Strange behaviour in Firefox, 所有其他浏览器都可以吗?