เราคุ้นเคยกับ window.location มากขึ้น มันมีคุณสมบัติเช่นโปรโตคอล, ชื่อโฮสต์, โฮสต์, พอร์ต, การค้นหา, แฮช, href, ชื่อพา ธ ฯลฯ แท็ก A เหมือนกับ window.location และมีคุณสมบัติดังกล่าวซึ่งสามารถช่วยให้เราวิเคราะห์ URL พูดคุยน้อยลงและเพิ่มรหัส
ฟังก์ชั่น parseurl (url) {var a = document.createelement ('a'); a.href = url; return {แหล่งที่มา: url, โปรโตคอล: a.protocol.replace (':', ''), โฮสต์: a.hostname, พอร์ต: a.port || '80' A.Search.replace (/^/?/, ''). แยก ('&'), len = seg.length, i = 0, s; for (; i <len; i ++) {ถ้า (! seg [i]) {ดำเนินการต่อ; (a.pathname.match (/// ([^//?#]+) $/i) || [, '']) [1], แฮช: A.hash.replace ('#', ''), เส้นทาง: a.pathname.replace (/^([^//] [, '']) [1], เซ็กเมนต์: A.PathName.replace (/^///, ''). แยก ('/')};}ที่อยู่ทดสอบ
console.log (parseurl ("http://www.w3school.com.cn/jsref/dom_obj_anchor.asp?type=2#id2"));
ผลลัพธ์มีดังนี้
การคัดลอกรหัสมีดังนี้:
-
ไฟล์: "dom_obj_anchor.asp",
แฮช: "id2",
โฮสต์: "www.w3school.com.cn"
params: {type: "2"}
PATH: "/JSREF/DOM_OBJ_ANCHOR.ASP"
พอร์ต: "80",
โปรโตคอล: "http",
แบบสอบถาม: "? type = 2"
ญาติ: "/jsref/dom_obj_anchor.asp?type=2#id2"
ส่วน: [0: "JSREF", 1: "DOM_OBJ_ANCHOR.ASP"],
ที่มา: http://www.w3school.com.cn/jsref/dom_obj_anchor.asp?type=2#id2
-