jQuery: If this HREF contains

前端 未结 6 1770
南笙
南笙 2021-01-30 20:51

Why can\'t I get this to work??

$(\"a\").each(function() {
    if ($(this[href$=\"?\"]).length()) {
        alert(\"Contains questionmark\");
    }
});


        
相关标签:
6条回答
  • 2021-01-30 21:06
    $("a").each(function() {
        if (this.href.indexOf('?') != -1) {
            alert("Contains questionmark");
        }
    });
    
    0 讨论(0)
  • 2021-01-30 21:11

    Try this:

    $("a").each(function() {
        if ($('[href$="?"]', this).length()) {
            alert("Contains questionmark");
        }
    });
    
    0 讨论(0)
  • 2021-01-30 21:16

    You could just outright select the elements of interest.

    $('a[href*="?"]').each(function() {
        alert('Contains question mark');
    });
    

    http://jsfiddle.net/mattball/TzUN3/

    Note that you were using the attribute-ends-with selector, the above code uses the attribute-contains selector, which is what it sounds like you're actually aiming for.

    0 讨论(0)
  • 2021-01-30 21:17

    Along with the points made by others, the $= selector is the "ends with" selector. You will want the *= (contains) selector, like so:

    $('a').each(function() {
        if ($(this).is('[href*="?"')) {
            alert("Contains questionmark");
        }
    });
    

    Here's a live demo ->

    As noted by Matt Ball, unless you will need to also manipulate links without a question mark (which may be the case, since you say your example is simplified), it would be less code and much faster to simply select only the links you want to begin with:

    $('a[href*="?"]').each(function() {
        alert("Contains questionmark");
    });
    
    0 讨论(0)
  • 2021-01-30 21:22

    use this

    $("a").each(function () {
        var href=$(this).prop('href');
        if (href.indexOf('?') > -1) {
            alert("Contains questionmark");
        }
    });
    
    0 讨论(0)
  • 2021-01-30 21:28

    It doesn't work because it's syntactically nonsensical. You simply can't do that in JavaScript like that.

    You can, however, use jQuery:

      if ($(this).is('[href$=?]'))
    

    You can also just look at the "href" value:

      if (/\?$/.test(this.href))
    
    0 讨论(0)
提交回复
热议问题