اجعل الروابط الخارجية برتقالية
اجعل جميع الروابط الخارجية برتقالية من خلال تعديل خاصية `النمط 'الخاصة بها.
الرابط يعتبر خارجيا إذا:
- Its
hrefhas://in it - But doesn’t start with
http://internal.com.
Example:
<a name="list">the list</a>
<ul>
<li><a href="/?originalUrl=https%3A%2F%2Far.javascript.info%2F%26quot%3Bhttp%3A%2F%2Fgoogle.com%26quot%3B%26gt%3Bhttp%3A%2F%2Fgoogle.com%26lt%3B%2Fa%26gt%3B%26lt%3B%2Fli%26gt%3B%2520%2520%26lt%3Bli%26gt%3B%26lt%3Ba%2520href%3D%26quot%3B%2Ftutorial%26quot%3B%26gt%3B%2Ftutorial.html%26lt%3B%2Fa%26gt%3B%26lt%3B%2Fli%26gt%3B%2520%2520%26lt%3Bli%26gt%3B%26lt%3Ba%2520href%3D%26quot%3Blocal%2Fpath%26quot%3B%26gt%3Blocal%2Fpath%26lt%3B%2Fa%26gt%3B%26lt%3B%2Fli%26gt%3B%2520%2520%26lt%3Bli%26gt%3B%26lt%3Ba%2520href%3D%26quot%3Bftp%3A%2F%2Fftp.com%2Fmy.zip%26quot%3B%26gt%3Bftp%3A%2F%2Fftp.com%2Fmy.zip%26lt%3B%2Fa%26gt%3B%26lt%3B%2Fli%26gt%3B%2520%2520%26lt%3Bli%26gt%3B%26lt%3Ba%2520href%3D%26quot%3Bhttp%3A%2F%2Fnodejs.org%26quot%3B%26gt%3Bhttp%3A%2F%2Fnodejs.org%26lt%3B%2Fa%26gt%3B%26lt%3B%2Fli%26gt%3B%2520%2520%26lt%3Bli%26gt%3B%26lt%3Ba%2520href%3D%26quot%3Bhttp%3A%2F%2Finternal.com%2Ftest%26quot%3B%26gt%3Bhttp%3A%2F%2Finternal.com%2Ftest%26lt%3B%2Fa%26gt%3B%26lt%3B%2Fli%26gt%3B%26lt%3B%2Ful%26gt%3B%26lt%3Bscript%26gt%3B%2520%2520%2F%2F%2520setting%2520style%2520for%2520a%2520single%2520link%2520%2520let%2520link%2520%3D%2520document.querySelector("a');
link.style.color = 'orange';
</script>
النتيجة يجيب أن تكون:
أولاً ، نحن بحاجة إلى العثور على جميع المراجع الخارجية.
هناك طريقتان.
الأول هو العثور على جميع الروابط باستخدام document.querySelectorAll ('a') ثم تصفية ما نحتاج إليه:
let links = document.querySelectorAll('a');
for (let link of links) {
let href="/?originalUrl=https%3A%2F%2Far.javascript.info%2Flink.getAttribute("href');
if (!href) continue; // no attribute
if (!href.includes('://')) continue; // no protocol
if (href.startsWith('http://internal.com')) continue; // internal
link.style.color = 'orange';
}
يرجى ملاحظة ما يلي: نستخدم link.getAttribute ('href'). ليس link.href ، لأننا نحتاج إلى القيمة من HTML.
… طريقة أخرى أبسط هي إضافة الشيكات إلى محدد CSS:
// look for all links that have :// in href
// but href doesn't start with http://internal.com
let selector = 'a[href*="://"]:not([href^="http://internal.com"])';
let links = document.querySelectorAll(selector);
links.forEach(link => link.style.color = 'orange');