JS基础操作
一、分支结构
1、if语句
if (条件表达式) {
代码块;
}
if (表达式1 ) {
代码块1 ;
} else {
代码块2 ;
}
if (表达式1 ) {
} else if (表达式2 ) {
}
...
else if (表达式2 ) {
} else {
}
if (表达式1 ) {
if (表达式2 ) {
}...
}...
2、switch语句
switch (表达式) {
case 值1 : 代码块1 ; break ;
case 值2 : 代码块2 ; break ;
default : 代码块3 ;
}
二、循环结构
1、for循环
for (循环变量①; 条件表达式②; 循环变量增量③) {
代码块④;
}
2、while循环
while (条件表达式) {
代码块;
}
3、do...while循环
do {
代码块;
} while (条件表达式);
4、for...in循环
obj = {"name" : "zero" , "age" : 8 }
for (k in obj) {
console .log (k, obj[k])
}
5、for...of循环
iter = ['a' , 'b' , 'c' ];
for (i of iter) {
console .log (iter[i])
}
6、break,continue关键词
break:结束本层循环
continue:结束本次循环进入下一次循环
三、异常处理
try {
易错代码块;
} catch (err) {
异常处理代码块;
} finally {
必须逻辑代码块;
}
throw "自定义异常"
四、函数初级
1、函数的定义
function 函数名 (参数列表) {
函数体;
}
var 函数名 = function (参数列表 ) {
函数体;
}
let 函数名 = (参数列表 ) => {
函数体;
}
(function (参数列表 ) {
函数体;
})
(function (参数列表 ) {
函数体;
})(参数列表);
2、函数的调用
3、函数的参数
function fn (a, b, c) {
console .log (a, b, c);
}
fn (100 );
function fn (a) {
console .log (a)
}
fn (100 , 200 , 300 )
function fn (a, b=20 , c, d=40 ) {
console .log (a, b, c, d);
}
fn (100 , 200 , 300 );
function fn (a, ...b) {
console .log (a, b);
}
fn (100 , 200 , 300 );
4、返回值
function fn () {
return 返回值;
}
五、事件初级
onload:页面加载完毕事件,只附属于window对象
onclick:鼠标点击时间
onmouseover:鼠标悬浮事件
onmouseout:鼠标移开事件
onfocus:表单元素获取焦点
onblur:表单元素失去焦点
六、JS选择器
1、getElement系列
document .getElementById ('id名' );
document .getElementsByClassName ('class名' );
document .getElementsByTagName ('tag名' );
2、querySelect系列
document .querySelector ('css语法选择器' );
document .querySelectorAll ('css语法选择器' );
3、id名
可以通过id名直接获取对应的页面元素对象,但是不建议使用
七、JS操作页面内容
innerText:普通标签内容(自身文本与所有子标签文本)
innerHTML:包含标签在内的内容(自身文本及子标签的所有)
value:表单标签的内容
outerHTML:包含自身标签在内的内容(自身标签及往下的所有)
八、JS操作页面样式
div.style .backgroundColor = 'red' ;
getComputedStyle (页面元素对象, 伪类).getPropertyValue ('background-color' );
getComputedStyle (页面元素对象, 伪类).backgroundColor ;
页面元素对象.currentStyle .getAttribute ('background-color' );
页面元素对象.currentStyle .backgroundColor ;
页面元素对象.className = "" ;
页面元素对象.className = "类名" ;
页面元素对象.className += " 类名" ;
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步