# js 入门学习
参考视频:https://www.bilibili.com/video/BV1JJ41177di/
参考资料:https://www.cnblogs.com/gh110/p/15153662.html
扩展:
- 数组的 for-each
- ```js
var arr = [15, 4, 3, 43, 21, 43, 2, 1, 3, 5];
arr.forEach((element) => {
console.log(element);
});
```
##js 实现点击按钮动态获取图片(随机显示)的效果
页面效果(每 2 秒换一张随机图片)
![1669963885351](https://gitee.com/shenqing0202/typora-cloud-notes/raw/master/Typora%E5%9B%BE%E7%89%87%E5%BA%93/1669963885351.png)
![1669963903301](https://gitee.com/shenqing0202/typora-cloud-notes/raw/master/Typora%E5%9B%BE%E7%89%87%E5%BA%93/1669963903301.png)
![1669963943420](https://gitee.com/shenqing0202/typora-cloud-notes/raw/master/Typora%E5%9B%BE%E7%89%87%E5%BA%93/1669963943420.png)
代码实现
```html
<html>
<head>
<title>Question 1</title>
</head>
<script>
//获取随机函数
function getRandomImage() {
//declare an array to store the images
var randomImage = new Array();
//insert the URL of images in array
randomImage[0] =
'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.lucydraw.com%2Fdata%2Fupload%2Fueditor%2F20171013%2F59e0371ca7b33.jpg&refer=http%3A%2F%2Fimg.lucydraw.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1672413002&t=d3e7feb53738628c5e1cbc6b9b216347';
randomImage[1] =
'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201808%2F19%2F20180819000255_NrATG.thumb.700_0.jpeg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1672412954&t=bed62887a2d42ea19f1a9c457420017c';
randomImage[2] =
'https://images.pexels.com/photos/142497/pexels-photo-142497.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500';
randomImage[3] =
'https://images.unsplash.com/photo-1543877087-ebf71fde2be1?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60';
randomImage[4] =
'https://wi.wallpapertip.com/wsimgs/156-1565522_puppies-desktop-wallpaper-desktop-background-puppies.jpg';
randomImage[5] =
'https://images.unsplash.com/photo-1501265976582-c1e1b0bbaf63?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60';
//generate a number and provide to the image to generate randomly
var number = Math.floor(Math.random() * randomImage.length);
//return the images generated by a random number
// return document.getElementById("result").innerHTML = '< img src="'+randomImage[number]+'" />';
return (document.getElementById('result').innerHTML =
'<img src="' + randomImage[number] + '">');
}
</script>
<body>
<h4>
Click the button to generate and display random images on the webpage
</h4>
<!-- call user-defined getRandomImage function after 2 seconds -->
<button onclick="setInterval(getRandomImage, 2000)">Generate Image</button>
<br />
<br />
<span id="result" align="center">
<!-- <img src="loop1.jpg"> -->
</span>
</body>
</html>
```
## switch 函数,获取输入框的数据,回显图片
```js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 思路:
首先我需要边弄个div 下边也弄个div 然后上div里边放input框 和提交按钮。
要注意不能有form表单,不然图片无法持续性回显!(form提交那个瞬间只是一瞬)
当我点击提交按钮的时候,就绑定了下方的函数!这个时候就调用swith函数!
函数的话设置的值就是显示出来的图片!也就是对应的img就可以啦
-->
<div style="width:1000px;height: 604px;border: solid 1px red;">
<div style="width:1000px;height: 200px;border: solid 1px red;">
<p>
请输入出生月份:<input type="text" name="month" id="month"/>
</p>
<button onclick = "mean()">提交</button>
</div>
<div style="width:1000px;height: 400px;border: solid 1px red; ">
<p>显示结果</p>
<br> <br>
<span id="result" align="center">
<!-- <img src="loop1.jpg"> -->
</span>
<!-- <img src="2.jpg"> -->
</div>
</div>
</body>
<script>
// return document.getElementById("result").innerHTML = '<img src="'+randomImage[number]+'">';
function mean() {
var month = document.getElementById("month");
switch(month.value){
case '1':return document.getElementById("result").innerHTML = '<img src="1.jpg">';
case '2':return document.getElementById("result").innerHTML = '<img src="2.jpg">';
case '3':return document.getElementById("result").innerHTML = '<img src="3.jpg">';
break;
default : return document.getElementById("result").innerHTML = '其他月份哦!';
}
}
</script>
</html>
```
效果:
![1670220159287](https://gitee.com/shenqing0202/typora-cloud-notes/raw/master/Typora%E5%9B%BE%E7%89%87%E5%BA%93/1670220159287.png)
改良版本(改了函数,让页面更简洁了)
```js
function mean() {
var month = document.getElementById('month');
var text1, text2;
switch (month.value) {
case '1':
text1 = '<img src="1.jpg">';
text2 = '<br> 一月代表康乃馨 <br>含义是:爱,魅力,尊敬之情';
break;
case '2':
text1 = '<img src="2.jpg">';
break;
case '3':
text1 = '<img src="3.jpg">';
break;
default:
text1 = '其他月份';
break;
}
document.getElementById('result').innerHTML = text1 + text2;
}
```
## 数组的相关操作
```js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
Refer to the following array operation:<br>
<button onclick="a()">click me</button><br>
i. Create an array styles with items "KFC" and "McDonald".<br>
<span id="result1"></span><br><br>
ii. Append "Burger King" to the end.<br>
<span id="result2"></span><br><br>
iii. Replace the value in the middle by "Bask Bear Coffee".<br>
Your code for finding the middle value should work for any arrays with odd length.<br>
<span id="result3"></span><br><br>
iv. Strip off the first value of the array and show it.<br>
<span id="result4"></span><br><br>
v. Add Zus Coffee and Kenny Roger to the array.<br>
<span id="result5"></span><br><br>
</body>
<script>
function a(){
var arr = ["KFC","McDonald"];
document.getElementById("result1").innerHTML = arr;
arr.push("Burger King");
document.getElementById("result2").innerHTML = arr;
//If the array length is odd
if(arr.length%2==1){
arr[(arr.length-1)/2]="Bask Bear Coffee";
}
document.getElementById("result3").innerHTML = arr;
delete arr[0];
document.getElementById("result4").innerHTML = arr;
arr.push("Zus Coffee","Kenny Roger");
document.getElementById("result5").innerHTML = arr;
}
</script>
</html>
```
运行结果
![1670377279087](https://gitee.com/shenqing0202/typora-cloud-notes/raw/master/Typora%E5%9B%BE%E7%89%87%E5%BA%93/1670377279087.png)
## 字符串相关操作
```js
<!DOCTYPE html>
<html lang="en">
<head>
<style>
img{
width: 150px;
height: 150px;
}
</style>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!--
a、 编写一个JavaScript函数,该函数接受字符串作为参数,并转换每个单词的第一个字母
字符串的小写和粗体。
示例字符串:“明天最好的准备是今天尽你最大的努力”
(学生可以根据自己的喜好使用其他字符串)
b、 编写一个JavaScript函数,将三个整数相加并赋值。
-->
</head>
<body>
<p>第一题:</p>
<button onclick="a('THE BEST PREPARATION FOR TOMORROW IS DOING YOUR BEST TODAY')">单词首字母小写加粗</button>
<br>
<span id="result"></span>
<p>第二题:</p>
<button onclick="b(1,2,3)">实现三个整数相加</button>
<br>
<span id="result1"></span>
</body>
<script>
var name;
function a(word){
let arr = word.split(" ");
let newArr = [];
for(let i = 0; i<arr.length;i++){
//单词的首字母实现小写并且加粗 ,后边不变。
newArr.push(arr[i][0].toLowerCase().bold(),arr[i].substring(1)," ")
//数组去掉逗号
name = newArr.join('');
}
// name = word.substring(0,1).toLowerCase().bold()+word.substring(1);
document.getElementById("result").innerHTML = name;
}
function b(a,b,c){
let d = a+b+c;
document.getElementById("result1").innerHTML = a+'+'+b+'+'+c+'='+d;
}
</script>
</html>
```
运行结果
![1670377389928](https://gitee.com/shenqing0202/typora-cloud-notes/raw/master/Typora%E5%9B%BE%E7%89%87%E5%BA%93/1670377389928.png)
## js 实现接收函数的返回值,下拉列表获取选择的值,函数获取参数
```js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.h{
width: 300px;
height: 300px;
margin: 0 auto;
background-color: firebrick;
}
</style>
</head>
<body>
<form name="myForm">
<select name="mySelect">
<option value="default">default</option>
<option value="yellow">yellow</option>
<option value="pink">pink</option>
</select>
</form>
<button onclick="c()">改变div的颜色</button>
<button onclick="a()">执行函数a</button>
<button onclick="b()">执行函数b</button>
<button onclick="c()">执行函数c</button>
<div class="h" id="h1">
</div>
</body>
<script>
var value1 ="happy";
function a(){
// 获取下拉框的值(js获取下拉列表的值)
value1=document.myForm.mySelect.value;
console.log(value1);
return value1;
}
function b(value1){
//接受a的返回值
// var f = a();
var f=value1;
console.log(f);
var tmp;
// 弄个函数动态返回
switch(f){
case 'default':
tmp="#ff0066";
break;
case 'yellow':
tmp="#ffff66";
break;
case 'pink':
tmp="#ff99cc";
break;
}
//返回16进制颜色值
return tmp;
}
function c(){
//获取16进制返回值
var m = b(a());
document.getElementById('h1').style.background=m;
}
</script>
</html>
```
![1673239252256](https://gitee.com/shenqing0202/typora-cloud-notes/raw/master/Typora%E5%9B%BE%E7%89%87%E5%BA%93/1673239252256.png)
> js 获取下拉框的值的第二种方法
```js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>js获取下拉框的值</title>
</head>
<body>
<select id="city">
<option value="0">default</option>
<option value="1">yellow</option>
<option value="2">pink</option>
</select>
<br/>
<div style="width: 100px;height: 100px;background-color: red;"></div>
<button onclick="a()">执行a函数</button>
<br/>
<span id="result">hhhh</span>
</body>
<script>
function a(){
var city=document.getElementById("city");
//然而这么使用会覆盖整个html的样式
// document.write(city[city.value].innerText);
console.log(city[city.value].innerHTML);
console.log(city[city.value].innerText);
document.getElementById("result").innerHTML=city[city.value].innerText;
}
</script>
</html>
```
效果
![1673240531755](https://gitee.com/shenqing0202/typora-cloud-notes/raw/master/Typora%E5%9B%BE%E7%89%87%E5%BA%93/1673240531755.png)
## js 更换 img 的 src 路径
- 给 img 设置 id 值, 例 mypic
- 再弄个按钮触发 js 函数
- 函数里是这句话,src 后的是需要被修改的值
```java
document.getElementById('mypic').src="../img/jiaran.png"
```
## [JS 和 JSP 之间值传递](https://www.cnblogs.com/chenyongjun/p/3541842.html)
> js/html 获取 jsp 中的变量值
- jsp 中的 java 函数(设置)
```java
<%
String s2 = "abc";
request.setAttribute("s2", s2);
%>
//或者更简单一点的
<%
String g1 = "我是测试嗷!!";
%>
```
- js 函数中
```js
//js获取jsp中的变量值(通过Attribute)
var s22 = '<%=request.getAttribute("s2")%>';
//或者,通过 "<%=javaCode%>" 引用jsp中的变量、方法等,注意:一定要加双引号
var g2 = '<%=g1%>';
alert(g2);
```
- 如果是 html 中获取 jsp 中 java 变量
```html
<%@ page language="java" pageEncoding="utf-8" %> <% String test1 = "happy girl";
%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<%--html获取jsp中java代码中的变量--%>
<button id="gl" value="<%=test1%>" onclick="a1()">测试按钮</button>
</body>
<script>
function a1() {
var a = document.getElementById('gl').value;
alert(a);
}
a;
</script>
</html>
```
这里得到的 s22 就是字符串"abc",弹出来的 g2 为 "我是测试嗷!!",弹出来的 a 为"happy girl";
> JSP 使用 JS 中的变量
由于 JSP 代码在服务器运行,无法直接使用客户端的 JS 代码中的变量。需先把客户端的变量提交到服务器,服务器再接收该变量。
案例如下:将 a.jsp 页面 JS 代码段的变量提交到服务器,JSP 片段再获取该变量。
-- 以下是 JSP 中 HTML 代码,用于将 JS 中变量存储到隐藏控件中
```html
<!-- 在form中设置隐藏控件,用来存储JS中的值 -->
<form name="frmApp" action="a.jsp" id="frmAppId" mothed="post"/>
<input id="test" type="hidden" name="test">
</form>
```
-- 以下是 JSP 中 JS 代码,通过表单将提交本页面(隐藏控件将被提交到服务器)
```js
<script language="javascript">
function setItemValue(){
var tmp = "testing";
document.getElementById("test").value = tmp; // 将JS变量值存储到隐藏控件中
}
function submit(){
var frm = document.getElementById("frmAppId"); // 获取表单
frm.submit(); // 对表单进行提交
}
</script>
```
-- 以下是 a.jsp 中在表单进行提交后,对变量进行接收的代码
```jsp
<%
String test = request.getParameter("test"); // test为隐藏控件名
%>
```
这也就是是,提交的时候,为什么改变 div 的颜色,只有一瞬间效果的原因,(就是因为 form 形式)
**注意:通过提交 form 形式使得 JSP 能够使用 JS 变量会刷新本页面,在页面不需要保持状态情况下可以考虑使用。否则,可以通过 Ajax 进行异步通信。**
详见文章:<http://www.cnblogs.com/chenyongjun/p/3541872.html>
> ajax 保持状态,异步通信(我测试了一下不太行)也可能是我不会用
aaa.jsp
```jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script>
var tmp = "testing";
function test(){
var xmlHttp;
// 处理Ajax浏览器兼容
if (window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
var url = "bbb.jsp?test=" + tmp; // 使用JS中变量tmp
console.log(url);
xmlHttp.open("post",url,true); //配置XMLHttpRequest对象
xmlHttp.onreadystatechange = function (){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
alert("调用成功!");
}else {
alert("调用失败!");
}
xmlHttp.send(null); // 发送请求
}
}
</script>
</head>
<body>
<input type="button" name="btTest1" value="测试" onclick="test()"/>
</body>
</html>
```
bbb.jsp
```jsp
<%@ page language="java" pageEncoding="utf-8" %>
<%
String test = request.getParameter("test"); // 接收aaa.jsp界面传来的test参数<br>
%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" name="test" value="<%=test%>" id="happy"> <!-- 引用jsp中变量 --><br>
</body>
<script>
var a=document.getElementById("happy").value;
alert(a);
</script>
</html>
```
## 点击删除按钮的时候拿到当前域的 id
你可以在添加每个用户时,将其 ID 值作为一个自定义属性添加到删除按钮上,然后在点击删除按钮时获取该自定义属性即可。具体来说,你可以将删除按钮代码改为:
```kotlin
<button class="del-btn" data-id="${user.id}">删除</button>
```
上述代码使用了 `data-id` 属性来存储用户的 ID 值。接着,在 JavaScript 代码中,你可以添加如下事件监听器:
```js
$(document).on('click', '.del-btn', function () {
const id = $(this).data('id');
console.log('Delete user with ID:', id);
// 在这里添加删除用户的代码
});
```
上述代码会监听 `class` 为 `del-btn` 的按钮的点击事件,获取该按钮上的 `data-id` 属性值,并将其打印到控制台中。你可以在控制台中查看输出结果以确认是否成功获取了 ID 值。注意,由于删除按钮是动态添加的,因此需要使用 `$(document).on()` 方法来绑定事件监听器。
标签:知识,innerHTML,js,getElementById,var,document,com From: https://www.cnblogs.com/Lovi/p/17717489.html