What does 'a [href ^ = "/"]' mean?

Is there a[href^="/"] regular expression in the code below?

Why does he have a ^ and what does he do?

What click events will / will not respond?

 $(document).on('click', 'a[href^="/"]', function(e) { e.preventDefault(); var href = $(e.currentTarget).attr('href'); console.log('click ' + href); Backbone.history.navigate(href, { trigger: true }); }); 

(source code)

+5
source share
3 answers

Q. Is there a[href^="/"] regular expression in the code below?

R. No, this is not a regular expression. This is a (CSS based) jQuery selector .

Q. Why does he have the symbol ^ and what does he do?

It has this symbol because it means startsWith .

Q. What click events will / will not respond?

R. It will respond to any tag a that has the href attribute that starts with / .


Note: this baseline code probably uses this selector to get all the internal links on the website and change their behavior for click-through navigation, and external links start with http / https .

+11
source

The ^ symbol indicates that the event will execute any link that starts with /

+2
source

a[href^="/"] - selector:

Selectors are patterns that correspond to elements in a tree, and as such form one of several technologies that can be used to select nodes in an XML document. Selectors have been optimized for use with HTML and XML and are intended for use in performance-critical code.

The ^ character is similar to the regex ^ anchor, although it is not a common expression. It is used as a special attribute selector:

6.3.2. Substring Match Attribute Selectors

There are three additional attribute selectors for matching substrings in the attribute value:

[ATT ^ = value]

Represents an element with the att attribute, the value of which begins with the prefix "val". If "val" is an empty string, the selector does not represent anything.

[ATT $ = value]

Represents an element with the attribute att, the value of which ends with the suffix "val". If "val" is an empty string, the selector does not represent anything.

[ATT * = value]

Represents an element with the attribute att whose value contains at least one instance of the substring "val". If "val" is an empty string, the selector does not represent anything.

This is an element attribute selector ( href is an attribute).

W3C Specification: Selectors Level 3

+2
source

Source: https://habr.com/ru/post/1232767/


All Articles