jQuery attribute selector: [x=y] or [x=z]

2019-03-26 07:33发布

问题:

I have the following jQuery selector:

$("a[href^='http://'],a[href^='https://']");

Is it possible to change this so that I don't need to specify a[href^= twice?

For example, something like:

$("a[href^='http://'||'https://']");

EDIT: My example of http and https should not be taken literally. I could be looking for values starting with y and z instead.

回答1:

Quite simple if you're willing to use a second function call:

$('a').filter('[href^="http://"],[href^="https://"]');

Or with tokens:

var startsWith = ['http://', 'https://'];
$('a').filter(function () {
    var i;
    for (i = 0; i < startsWith.length; i++) {
        if ($(this).is('[href^="' + startsWith[i] + '"]')) {
            return true;
        }
    }
    return false;
});

Or with a custom expression:

$.expr[':']​​​​​​.hrefStartsWith = function (ele, i, info) {
    var tokens;
    tokens = info[3].split(',');
    for (i = 0; i < tokens.length; i++) {
        if ($(ele).is('[href^="' + tokens[i] + '"]')) {
            return true;
        }
    }
    return false;
};

Which would be used as:

$('a:hrefStartsWith(http://,https://)')


回答2:

Fiddle: http://jsfiddle.net/X8CYQ/


You should be able to use something like this:

$.expr[':'].exturl = function(obj) {
   return (/^https?:\/\//i).test($(obj).attr("href"));
}

Then use the selector like this:

$("a:exturl")

HTML:

<a href="http://www.google.com">External link #1</a><br />
<a href="ftp://www.donotinclude.dk">No match link #1</a><br />
<a href="?nope">No match link #2</a><br />
<a href="https://www.google.dk">External link #2</a><br />
<a href="http://www.google.se">External link #3</a><br />
<a href="ssh://whywouldyouevendothis">No match link #3</a><br />
<a href="https://www.google.co.uk">External link #4</a><br />
<a href="http://www.facebook.com">External link #5</a><br />
<a href="/index.html">No match link #4</a><br />
<a href="https://www.facebook.com">External link #6</a><br />​

JS:

$.expr[':'].exturl = function(obj) {
    return (/^https?:\/\//i).test($(obj).attr("href"));
}
$(document).ready(function() {
    $("a:exturl").css("color", "red");
});​


回答3:

You can simply do

$("a[href^='http']")

As the href^= just means "starts with" unless you have a need to be sure :// is included as well.

Here is an example with other attributes and values:

http://jsbin.com/owehow/2/edit



回答4:

You can't do this in jQuery by default .. it doesn't have any sort of "or" condition for selectors (except for the comma, sort of, which is what you want to avoid).

You could create a custom filter if you wanted to:

http://jsfiddle.net/yJZDg/

This is very overkill unless you need to do this kind of thing a lot. The example will also only work for an exact match. You would have to tweak for a "starts with" or some other kind of match, but the idea is there.