关于$(this).attr("value");
package com.imooc.ajax;
public class Song {
private String name;
public Song() {
}
public Song(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.imooc.ajax;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
/**
* Servlet implementation class Text2
*/
@WebServlet("/text2")
public class Text2 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Text2() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Song> list = new ArrayList<Song>();
String type = request.getParameter("name");
if (type != null && type.equals("流行歌曲")) {
list.add(new Song("稻香"));
list.add(new Song("晴天"));
list.add(new Song("告白气球"));
} else if (type != null && type.equals("经典歌曲")) {
list.add(new Song("千千阙歌"));
list.add(new Song("傻女"));
list.add(new Song("七友"));
} else if (type != null && type.equals("摇滚歌曲")) {
list.add(new Song("一块红布"));
list.add(new Song("假行僧"));
list.add(new Song("新长征路上的摇滚"));
} else {
System.out.println("error");
}
String json = JSON.toJSONString(list);
System.out.println(json);
response.setContentType("text/html;charset=utf-8");
response.getWriter().println(json);
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<input type="button" id="1" value="流行歌曲">
<input type="button" id="2" value="经典歌曲">
<input type="button" id="3" value="摇滚歌曲">
<div style="text-align: center" id="show"></div>
<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(function() {
$("input").click(function() {
var name = $(this).attr("value");
$("#show").empty();
$.ajax({
"url" : "/ajax/text2",
"type" : "get",
"data" : {"name" : name},
"dataType" : "json",
"success" : function(json) {
for (var i = 0; i < json.length; i++) {
$("#show").append("<h1>" + json[i].name + "</h1>");
}
}
})
})
})
</script>
</body>
</html>
虽然实现了但突然对
var name = $(this).attr("value");
这句不太理解,这个不是获取input对应value的属性值吗,就是流行摇滚经典歌曲那些,那在
"data" : {"name" : name},
中的json键值对中的值,name是什么,突然混乱了
14
收起
正在回答
1回答
同学你好,1. 已完成练习,继续加油!
2. attr() 方法设置或返回被选元素的属性值,$(this)代表当前元素,在当前代码中$(this)代表的是触发了click时间的input元素。
3. data是传递的参数,而{"name" : name}"name"是参数名,而name是参数值(通过 $(this).attr("value");获取当前元素的属性值)
2. 从网页搭建入门JavaWeb
- 参与学习 人
- 提交作业 676 份
- 解答问题 9666 个
本阶段将从前端网页搭建入手,到Java Web基础,前后端结合助你完成Java Web小白的蜕变!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星