简体   繁体   English

jQuery,如果任何元素的父母的href都以

[英]jQuery if any of an element's parents' href begins with

So what I'm trying to achieve is a way to check if any of an element's parents' href begin with something. 因此,我试图实现的是一种检查元素的父母的href是否以某东西开头的方法。 Here's how far I've come: 这是我走了多远:

$('.element').click(function(e){
    if($(this).is('[href^="X"')){
        // How to check if the clicked element's href begins with X
    }
});

But this is not what I want. 但这不是我想要的。 I wanna check if any of the element's parents have a href beginning with something. 我想检查元素的任何父母是否具有以某内容开头的href。

Any ideas? 有任何想法吗?

Gustaf 古斯塔夫

I'd suggest, given that nesting an <a> element is invalid so that there can be only one ancestor <a> element (or no ancestor <a> elements, obviously): 我建议,鉴于嵌套<a>元素是无效的,因此只能有一个祖先<a>元素(或者显然没有祖先<a>元素):

$('.element').click(function(e){
    // here we use a terribly-, but meaningfully-, named variable
    // to hold the Boolean result of the assessment;
    // the assessment looks from the clicked element up through
    // the ancestors for the first <a> element matching the
    // attribute-starts-with selector ([href^=x])
    // this will return either 1 or 0 elements.
    // we check the length; if it's equal to 1 then the ancestor
    // has an href starting with x, if it's 0 then there is either
    // no ancestor <a> element or no ancestor <a> element with a
    // href matching the attribute-starts-with selector:
    var ancestorAnchorStartsWithX = $(this).closest('a[href^=x]').length === 1;
});

It's worth noting, as @A. 值得注意的是,@ A。 Wolff did , in the comments below, that: 沃尔夫在以下评论中做到了:

closest() [checks the] element itself too. closest() [也检查]元素本身。

Which means that if the clicked element itself matches the selector supplied to closest (and is therefore an <a> element with an href beginning with x ) then the assessment will return true, even though it's not an ancestor element. 这意味着,如果clicked元素本身与提供的最接近的选择器匹配(因此是一个<a>元素,其hrefx开头),则评估将返回true,即使它不是祖先元素也是如此。 I considered this a feature – while writing out the selector – but I forgot to detail that in the answer itself. 在写出选择器时,我认为这是一项功能,但我忘记在答案中详细说明。

If this is considered a bug, then an option using parents('a[href^=x]') in place of closest('a[href^=x]') will be more appropriate to your use-case. 如果这被认为是一个错误,那么使用parents('a[href^=x]')代替closest('a[href^=x]')将更适合您的用例。

References: 参考文献:

 $(".element").click(function(e) { var res = $(this).parents("[href^=X]").is("*"); console.log(res); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <a href="Xabc123"> <div class="element">click</div> </a> 

This is what you want: 这就是你想要的:

$('.element').click(function(e){
      var $parents=$(this).parents();
      var matches=$parents.filter('[href^="x"]');
      if(matches.length){
      }

    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM