目录
encodeURIComponent() 和 decodeURIComponent()
【兼容性封装】stopPropagation和cancelBubble
非 VIP 用户可前往公众号“前端基地”进行免费阅读,文章链接如下:
29JavaScript 核心技巧大揭秘!从 DOM 操作到事件机制全掌握
encodeURIComponent() 和 decodeURIComponent()
encodeURIComponent() 和 decodeURIComponent() 是 JavaScript 中用于处理 URL 编码的两个重要函数,它们在处理包含特殊字符的 URL 参数时非常有用。
encodeURIComponent():将字符串编码为符合 URL 安全规范的格式,适用于编码 URL 中的参数值(如查询字符串、表单数据等)。
编码规则
保留字符:不会编码 - _ . ! ~ * ' ( )。
特殊字符:会编码所有其他字符,包括 / ? : @ & = + $ , # 等。
空格:会被编码为 %20(而非 +,与表单编码不同)。
decodeURIComponent():将 encodeURIComponent() 编码的字符串还原为原始字符串。
示例代码如下:
<script type="text/javascript">
window.onload=function(){
var url="http://www.qianduanjidi.com";
// 编码encodeURIComponent()
var enUrl=encodeURIComponent(url);
console.log(enUrl);//https%3A%2F%2F2.zoppoz.workers.dev%3A443%2Fhttp%2Fwww.qianduanjidi.com
// 解码decodeURIComponent()
var deUrl=decodeURIComponent(enUrl);
console.log(deUrl);//http://www.qianduanjidi.com
}
</script>
html结构访问
在 JavaScript 中,可以通过document对象访问 HTML 文档的各个部分。这种访问方式允许开发者动态获取或修改页面内容、样式和结构。
示例代码如下:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>HTML结构访问演示</title>
<script>
window.onload = function() {
// 访问文档元信息
console.log("文档标题:", document.title);
console.log("head元素:", document.head);
&