How exactly is [att~=val] different from [att*=val

2019-04-11 11:39发布

问题:

Maybe I am missing something, but they seem similar. If you use for example...

a[alt~="thumb"]

or...

a[alt*="thumb"]

What can I narrow my selection down to differently? I am at the understanding that ~ gives you a partial match in the quotes while the * gives you a partial match. I am going to fiddle with the code a little, but since I could not find a question on the subject here, thought it would make a good topic either way.

回答1:

From the JQuery help (which supports the standard selectors):

a[alt~="thumb"]

Description: Selects elements that have the specified attribute with a value containing a given word, delimited by spaces. This selector matches the test string against each word in the attribute value, where a "word" is defined as a string delimited by whitespace. The selector matches if the test string is exactly equal to any of the words.

a[alt*="thumb"]

Description: Selects elements that have the specified attribute with a value containing the a given substring. This is the most generous of the jQuery attribute selectors that match against a value. It will select an element if the selector's string appears anywhere within the element's attribute value. Compare this selector with the Attribute Contains Word selector (e.g. [attr~="word"]), which is more appropriate in many cases.

Basically the selector ~= only matches if the value is found surrounded by white space. The selector *= matches if the value is found anywhere.

<div alt='heading navigation'>
<div alt='head'>

div[alt~='head'] would match only the second div, but div[alt*='head'] would match both.



回答2:

[att~=value] is a contains word selector.

So a [alt="foo"] selector will match <a alt="foo bar"> but will not match <a alt="foobar">.

[alt*="foo"] will match both though, because this doesn't discriminate on words or whatever. As long as it's in the value, it hits.