Key Points
cite
Block reference
function extractBlockquoteCitations() { var quotes = document.getElementsByTagName('blockquote'); for (var i = 0; i < quotes.length; i++) { var cite = quotes[i].getAttribute('cite'); if (cite) { var a = document.createElement('a'); a.setAttribute('href', cite); a.setAttribute('title', cite); a.appendChild(document.createTextNode('Source')); var p = document.createElement('p'); p.className = 'blockquotesource'; p.appendChild(a); quotes[i].appendChild(p); } } }
var quotes = document.getElementsByTagName('blockquote');
This line of code uses the DOM method getElementsByTagName
to find all block reference elements in the current page and assign them to an array named quotes
(actually HTMLCollection, but it is a data structure that behaves like an array).
for (var i = 0; i < quotes.length; i ) { ... }
Now we are traversing the collected block reference node. Each time we loop, we use the getAttribute
method to retrieve the cite attribute from the element. If the cite property is set, we will proceed to the interesting part: Create a "source" link at the bottom of the citation.
var a = document.createElement('a'); a.setAttribute('href', cite); a.setAttribute('title', cite);
When we want to dynamically add new HTML elements to the page using the DOM, the correct way to do this is to create these elements programmatically using the createElement
method. The above lines create a new 'a' element and assign it the href and title attributes, both of which are set as URLs of the citation.
a.appendChild(document.createTextNode('Source'));
We want the link element to contain some text that users can click to activate the link. The original text node is created using the createTextNode
method. DOM treats HTML elements as making up a tree, so to add text to our newly created link, we need to call its appendChild
method.
var p = document.createElement('p'); p.className = 'blockquotesource'; p.appendChild(a);
To allow us to flexibly style new links using CSS, we can wrap it in a paragraph element. The above code creates such an element, sets its class to "blockquotesource" to provide a CSS hook, and then adds the link to it using appendChild
. At this point, the new document fragment we built is equivalent to the following HTML:
<code><p> <a href="https://www.php.cn/link/a725c77dfdec0a53250d0709ed36e1fe" title="https://www.php.cn/link/a725c77dfdec0a53250d0709ed36e1fe">Source</a> </p>
Source
At present, our snippet is still invisible because although we created it in memory, we have not attached it to our documentation yet. This is what the last line in the function does:
quotes[i].appendChild(p);
quotes[i]
appendChild
is the block reference element we are currently working on.
There are two more steps. First, we need to run the above function when the page is first loaded. There are many ways to achieve this. The easiest way is to add a call to the function to the onload property of the document body element:
This works fine, but we can do it better. Since our JavaScript functions will be hosted in external files, wouldn't it be more meaningful for external files to cause functions to run? The naive approach is to use the following JavaScript code:
window.onload = extractBlockquoteCitations;
//
Note that we provide the name of the function, but ignore the () at the end, which will cause the function to execute. JavaScript supports functional programming style, which means that functions can be passed as parameters, stored in data structures, and can even be returned from other functions like any other data object. I will discuss this topic more in future posts, but the result is that assigning the function to window.onload
will cause it to be executed after the page loads.
However, this solution also has one drawback. If you want to use multiple scripts executed after the page load is completed on a given page, the last script that registers itself to window.onload
will be the only script that executes. What is really needed is a way to attach our function to the onload handler of the window object without overwriting what is already there. Unfortunately, Internet Explorer and other browsers differ in how to handle such dynamic event attachments; luckily, Scott Andrew published a function that can handle these differences. The following is the function:
function extractBlockquoteCitations() { var quotes = document.getElementsByTagName('blockquote'); for (var i = 0; i < quotes.length; i++) { var cite = quotes[i].getAttribute('cite'); if (cite) { var a = document.createElement('a'); a.setAttribute('href', cite); a.setAttribute('title', cite); a.appendChild(document.createTextNode('Source')); var p = document.createElement('p'); p.className = 'blockquotesource'; p.appendChild(a); quotes[i].appendChild(p); } } }
The following is the code to add our blockquotes function to the load event of the window object:
addEvent(window, 'load', extractBlockquoteCitations);
The last step is to style the citation with CSS. Here is a relatively simple CSS code snippet that handles block references:
function addEvent(obj, evType, fn){ if (obj.addEventListener){ obj.addEventListener(evType, fn, false); return true; } else if (obj.attachEvent){ var r = obj.attachEvent("on"+evType, fn); return r; } else { return false; } }
The finished product can be viewed here.
Now, let's consider a more advanced dynamic effect - the panel switcher. The goal here is to place multiple panels on the page (using div tags) and display only one panel at a time. A set of always visible links can be used to select the currently displayed panel. This is useful for building tabbed interfaces to browse a range of related screens without refreshing the page every time you select a tab.
Whenever using JavaScript to enhance your page, you need to remember a good rule that the page must still be available even if JavaScript is disabled. In this case, this means that the ideal solution should work as advertised when JavaScript is enabled, but in a non-JavaScript environment, all panels should be displayed on the page, each link directly linking to the relevant panel, and using URL snippets.
Then, this is the easiest mark that can work:
Surprisingly, the above is almost all the markup we need to hook some JavaScript to create the desired effect. We can continue with the code above, but let's add a class to the link to make it clear that we want to perform special operations on them:
<a href="https://www.php.cn/link/65dfa16ba6de9bdb34ea435c9fe2a425" class="toggle">Panel 1</a> | <a href="https://www.php.cn/link/379d08c7a38df48c777c07ea990a3bcf" class="toggle">Panel 2</a>
//
The following is how JavaScript works. When the page loads, the script will scan all links on the page for any links that contain "toggle" in its class. For any links found, the href attribute is checked and the specified element is positioned and added to the target element array. All other elements except the first element will be "closed", so when the page loads, only the first panel will remain visible. The link itself will attach a JavaScript event handler so that when they are activated, their corresponding panels can be displayed.
The complete script can be viewed here. The following is a step-by-step explanation of how the code works.
var et_toggleElements = [];
The first line creates a global empty array that will save references to the panel elements on the page. Because this script has global variables and many functions, we prefix each function with "et_" (for "easy toggle") - which reduces the possibility that our function will have name conflicts with other scripts loaded on the same page.
/* Initialisation */ function et_init() { var i, link, id, target, first; first = true; for (i = 0; (link = document.links[i]); i ) { ... }
So far, we have initialized some variables, set the first flag to true, and start iterating over all links in the document. Declaring variables using var
is very important because it ensures that the variable is local to the function. Without this step, they will be globally accessible and may interfere with other scripts.
if (/btoggleb/.exec(link.className)) { ... }
This condition checks whether the currently linked class contains "toggle". We use regular expressions instead of just checking link.className == 'toggle'
, because class properties can contain multiple classes, separated by spaces. /btoggleb/
is a regular expression; b
partially matches "word boundary", which may be the beginning or end of a space or string.
id = link.href.split('#')[1];
If the linked class list contains toggle, we assume that the target of the link is a URL snippet.
link.href.split('#')
Split the link href at the # tag - we know that the part we are interested in is after #, so we directly index the result array using [1]
to extract the target ID.
target = document.getElementById(id); et_toggleElements[et_toggleElements.length] = target;
Here, we make another assumption that the link indicates the element does exist. We use the getElementById()
method to get the element and then add it to our array of elements by assigning it to an array index equal to the current length of the array. This works because the array starts indexing from 0, but the array length counts from 1; therefore, the length of the array is also the index of the next empty slot in the array.
if (first) { first = false; } else { target.style.display = 'none'; }
This is where the first logo we defined earlier comes into play. We want the first panel on the website to remain visible, while the others are hidden using JavaScript equivalent to "display: none" in CSS. This flag allows us to do this.
link.onclick = et_toggle;
Finally, we assign the et_toggle
function to the linked onclick
event, causing the function to be called each time the link is activated. The next step is to define the function.
function extractBlockquoteCitations() { var quotes = document.getElementsByTagName('blockquote'); for (var i = 0; i < quotes.length; i++) { var cite = quotes[i].getAttribute('cite'); if (cite) { var a = document.createElement('a'); a.setAttribute('href', cite); a.setAttribute('title', cite); a.appendChild(document.createTextNode('Source')); var p = document.createElement('p'); p.className = 'blockquotesource'; p.appendChild(a); quotes[i].appendChild(p); } } }
Again, we use the split
method to extract the ID from the link.
Now that we know which panel to display, we can iterate through our element array and close all other elements except the one whose ID matches the ID of the desired panel.
By returning false, we prevent the link from being actually followed when activated, which may cause undesired jumps on pages viewed in the browser.
The last step is to register the addEvent
function to the load event of the window using the et_init
function described earlier.
addEvent(window, 'load', et_init);
You can view the running completion code here.
In this article, we see two ways that well-structured markers can be used with JavaScript and W3C DOM for useful effects. I hope this post inspires you to find new ways to use JavaScript and smart tagging.
There are many other excellent examples of JavaScript effects based on structured tags. Here are some examples worth paying attention to:
Structured tags in JavaScript are the use of HTML elements to describe the content and structure of a web document. These elements include titles, paragraphs, lists, and more. JavaScript can manipulate these elements to create dynamic and interactive web pages. For example, JavaScript can change the content of an HTML element, change the style (CSS) of an HTML element, and even add new HTML elements.
JavaScript interacts with HTML elements through the Document Object Model (DOM). DOM represents the structure of a web page, which JavaScript can operate. For example, JavaScript can use the document.createTextNode()
method to create a new text node and then append it to an existing HTML element.
A text node in JavaScript is a node type that represents the text content of an element or attribute. It can be created using the document.createTextNode()
method. This method creates a new text node that can be attached to an existing HTML element, allowing you to dynamically add text to the web page.
JavaScript can be added to HTML in several ways. You can use the <script></script>
tag to include it directly in an HTML file, or you can use the <script></script>
attribute of the src
tag to link to an external JavaScript file. You can also use event properties such as onclick
or onload
to run JavaScript code when a specific event occurs.
document.createTextNode()
method? document.createTextNode()
method is used to create a new text node. First call this method with the text you want to add as a parameter. This returns a new text node, which can then be attached to an existing HTML element using the appendChild()
method.
Document Object Model (DOM) is the programming interface for HTML and XML documents. It represents the structure of a document as a tree of objects, each object representing a part of the document. JavaScript can interact with the DOM to manipulate the content and structure of a web page.
You can change the content of an HTML element using the innerHTML
attribute in JavaScript. This property can be used to get or set the HTML content of an element. For example, if there is an element with id "myElement", it can be changed like this: document.getElementById('myElement').innerHTML = 'New content';
.
You can change the style of HTML elements using the style
attribute in JavaScript. This property is an object that contains all CSS properties of the element. For example, if there is an element with id "myElement", it can be changed like this: document.getElementById('myElement').style.color = 'red';
.
You can add new HTML elements using the createElement()
method in JavaScript. This method creates a new element, which can then be attached to an existing element using the appendChild()
method. For example, you can create a new paragraph and add it to the body of the document as follows: var p = document.createElement('p'); document.body.appendChild(p);
.
The event attribute in JavaScript is used to define the JavaScript code to run when a specific event occurs. These events may include clicking a button (onclick
), loading a page (onload
), or moving the mouse over an element (onmouseover
), etc. The code for the event is defined directly in the properties of the HTML element.
The above is the detailed content of Enhancing Structural Markup with JavaScript. For more information, please follow other related articles on the PHP Chinese website!