【尚筹网】IDEA版实现(四)角色维护

由于尚硅谷的视频是通过Eclipse软件来做的,其中有些操作与IDEA上有所区别,所以我在这里将IDEA区别于Eclipse的操作、操作过程中涉及的源码(与视频的源码略有出入)以及大家可能遇到的种种问题分享给大家,这些源码在我这里均是通过测试的,仅供参考!

1 创建数据库表

在SQLyog中创建:

CREATE TABLE `t_role` (
    id INT NOT NULL AUTO_INCREMENT,
    NAME CHAR(100),
    PRIMARY KEY (id)
);

2 mybatis逆向工程

修改reverse\src\main\resources\generatorConfig.xml

<!--  数据库表名字和我们的 entity 类对应的映射指定 -->
<table tableName="t_admin" domainObjectName="Admin" />
<table tableName="t_role" domainObjectName="Role" />

在IDEA右侧的maven project找到mybatis-generator:generate并点击运行,生成文件:

在这里插入图片描述

在这里插入图片描述

修改reverse\src\main\java\com\atguigu\crowd\entity\Role.java

public Role() {

    }

    public Role(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Role{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

将Role.java与RoleExample.java放入entity\src\main\java\com\atguigu\crowd\entity中

将RoleMapper.java放入component\src\main\java\com\atguigu\crowd\mapper中

将RoleMapper.xml放入webui\src\main\resources\mybatis\mapper中

3 后端部分

3.1 RoleMapper

修改component\src\main\java\com\atguigu\crowd\mapper\RoleMapper.java

List<Role> selectRoleByKeyword(String keyword);

修改webui\src\main\resources\mybatis\mapper\RoleMapper.xml

<select id="selectRoleByKeyword" resultMap="BaseResultMap">
    select id, name from t_role
    where name like concat("%",#{keyword},"%")
  </select>

3.2 RoleService

在component\src\main\java\com\atguigu\crowd\service\api新建RoleService.java

package com.atguigu.crowd.service.api;

import com.atguigu.crowd.entity.Role;
import com.github.pagehelper.PageInfo;

public interface RoleService {
    PageInfo<Role> getPageInfo(Integer pageNum, Integer pageSize, String keyword);
}

在component\src\main\java\com\atguigu\crowd\service\impl新建RoleServiceImpl.java

package com.atguigu.crowd.service.impl;

import com.atguigu.crowd.entity.Role;
import com.atguigu.crowd.mapper.RoleMapper;
import com.atguigu.crowd.service.api.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Override
    public PageInfo<Role> getPageInfo(Integer pageNum, Integer pageSize, String keyword) {
        // 1.开启分页功能
        PageHelper.startPage(pageNum,pageSize);
        // 2.执行查询
        List<Role> roleList = roleMapper.selectRoleByKeyword(keyword);
        // 3.封装为PageInfo对象返回
        return new PageInfo<>(roleList);
    }
}

在component\src\main\java\com\atguigu\crowd\mvc\handler新建RoleHandler.java

package com.atguigu.crowd.mvc.handler;

import com.atguigu.crowd.entity.Role;
import com.atguigu.crowd.service.api.RoleService;
import com.atguigu.crowd.util.ResultEntity;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class RoleHandler {

    @Autowired
    private RoleService roleService;

    @RequestMapping("/role/get/page/info.json")
    public ResultEntity<PageInfo<Role>> getPageInfo(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                    @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                                    @RequestParam(value = "keyword", defaultValue = "") String keyword) {
        // 调用service获取分页数据
        PageInfo<Role> pageInfo = roleService.getPageInfo(pageNum,pageSize,keyword);
        
        // 封装到ResultEntity对象中返回(如果上面的操作抛出异常,交给异常映射机制处理)
        return ResultEntity.successWithData(pageInfo);
    }
}

3.3 测试

直接打开:http://localhost:8080/atcrowdfunding02_admin_webui_war_exploded/role/get/page/info.json,提前添加一些数据,会显示出来

在这里插入图片描述

4 前端部分

4.1 新建页面

修改webui\src\main\resources\spring-web-mvc.xml

<mvc:view-controller path="/role/to/page.html" view-name="role-page"/>

在webui\src\main\webapp\WEB-INF新建role-page.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<%@include file="include-head.jsp" %>

<body>
<%@include file="include-nav.jsp" %>
<div class="container-fluid">
    <div class="row">
        <%@include file="include-sidebar.jsp" %>
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title"><i class="glyphicon glyphicon-th"></i> 数据列表</h3>
                </div>
                <div class="panel-body">
                    <form class="form-inline" role="form" style="float:left;">
                        <div class="form-group has-feedback">
                            <div class="input-group">
                                <div class="input-group-addon">查询条件</div>
                                <input class="form-control has-success" type="text" placeholder="请输入查询条件">
                            </div>
                        </div>
                        <button type="button" class="btn btn-warning"><i class="glyphicon glyphicon-search"></i> 查询</button>
                    </form>
                    <button type="button" class="btn btn-danger" style="float:right;margin-left:10px;"><i class=" glyphicon glyphicon-remove"></i> 删除</button>
                    <button type="button" class="btn btn-primary" style="float:right;" οnclick="window.location.href='form.html'"><i class="glyphicon glyphicon-plus"></i> 新增</button>
                    <br>
                    <hr style="clear:both;">
                    <div class="table-responsive">
                        <table class="table  table-bordered">
                            <thead>
                            <tr>
                                <th width="30">#</th>
                                <th width="30"><input type="checkbox"></th>
                                <th>名称</th>
                                <th width="100">操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr>
                                <td>1</td>
                                <td><input type="checkbox"></td>
                                <td>PM - 项目经理</td>
                                <td>
                                    <button type="button" class="btn btn-success btn-xs"><i class=" glyphicon glyphicon-check"></i></button>
                                    <button type="button" class="btn btn-primary btn-xs"><i class=" glyphicon glyphicon-pencil"></i></button>
                                    <button type="button" class="btn btn-danger btn-xs"><i class=" glyphicon glyphicon-remove"></i></button>
                                </td>
                            </tr>
                            </tbody>
                            <tfoot>
                            <tr>
                                <td colspan="6" align="center">
                                    <ul class="pagination">
                                        <li class="disabled"><a href="#">上一页</a></li>
                                        <li class="active"><a href="#">1 <span class="sr-only">(current)</span></a></li>
                                        <li><a href="#">2</a></li>
                                        <li><a href="#">3</a></li>
                                        <li><a href="#">4</a></li>
                                        <li><a href="#">5</a></li>
                                        <li><a href="#">下一页</a></li>
                                    </ul>
                                </td>
                            </tr>

                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

修改webui\src\main\webapp\WEB-INF\include-sidebar.jsp

<a href="role/to/page.html"><i class="glyphicon glyphicon-king"></i> 角色维护</a></li>

4.2 新建分页

修改webui\src\main\webapp\WEB-INF\role-page.jsp

<%@include file="include-head.jsp" %>
<link rel="stylesheet" href="css/pagination.css">
<script type="text/javascript" src="jquery/jquery.pagination.js"></script>
<script type="text/javascript" src="js/my-role.js"></script>
<script type="text/javascript">
    $(function (){
        // 1.为分页操作准备初始化数据
        window.pageNum = 1;
        window.pageSize = 5;
        window.keyword = "";

        // 2. 调用分页函数,实现分页效果
        generatePage();
    });
</script>
<tbody id="rolePageBody"></tbody>
<tfoot>
    <tr>
        <td colspan="6" align="center">
            <div id="Pagination" class="pagination"><!--这里显示分页--></div>
        </td>
    </tr>
</tfoot>

在webui\src\main\webapp\crowd新建my-role.js

// 执行分页,生成页面效果,任何时候调用这个函数都会重新加载页面
function generatePage() {

  // 1.获取分页数据
  var pageInfo = getPageInfoRemote();

  // 2.填充表格
  fillTableBody(pageInfo);

}

// 远程访问服务器端程序获取pageInfo数据
function getPageInfoRemote() {

  console.log("pageNum="+window.pageNum);
  // 调用$.ajax()函数发送请求并接受$.ajax()函数的返回值
  var ajaxResult = $.ajax({
    url: "role/get/page/info.json",
    type: "post",
    data: {
      "pageNum": window.pageNum,
      "pageSize": window.pageSize,
      "keyword": window.keyword
    },
    async: false,
    dataType: "json"
  });
  console.log(ajaxResult);

  // 判断当前响应状态码是否为200
  var statusCode = ajaxResult.status;

  // 如果当前响应状态码不是 200,说明发生了错误或其他意外情况,显示提示消息,让 当前函数停止执行
  if (statusCode != 200) {
    layer.msg("失败!响应状态码="+statusCode+" 说明信息="+ajaxResult.statusText);
    return null;
  }
  // 如果响应码为200,说明请求处理成功,获取pageInfo
  var resultEntity = ajaxResult.responseJSON;

  // 从resultEntity属性中获取result属性
  var result = resultEntity.result;

  // 判断result是否成功
  if (result == "FAILED"){
    layer.msg(resultEntity.message);
    return null;
  }

  // 确认 result 为成功后获取 pageInfo
  var pageInfo = resultEntity.data;

  // 返回 pageInfo
  return pageInfo;
}

// 填充表格
function fillTableBody(pageInfo) {

  // 清除 tbody 中的旧的内容
  $("#rolePageBody").empty();

  // 这里清空是为了让没有搜索结果时不显示页码导航条
  $("#Pagination").empty();

  // 判断pageInfo是否有效
  if (pageInfo == null || pageInfo.list == null || pageInfo.list.length === 0){
    $("#rolePageBody").append("<tr><td colspan='4' align='center'>抱歉!没有查询到您搜索的数据</td></tr>");
    return;
  }
  // 使用pageInfo的list属性填充tBody
  for (var i = 0; i < pageInfo.list.length; i++) {

    var role = pageInfo.list[i];
    var roleId = role.id;
    var roleName = role.name;

    var numberTd = "<td>"+(i+1)+"</td>";
    var checkboxTd = "<td><input type='checkbox'></td>";
    var roleNameTd = "<td>"+roleName+"</td>";

    var checkBtn = "<button type=\"button\" class=\"btn btn-success btn-xs\"><i class=\" glyphicon glyphicon-check\"></i></button>";
    var pencilBtn = "<button type=\"button\" class=\"btn btn-primary btn-xs\"><i class=\" glyphicon glyphicon-pencil\"></i></button>";
    var removeBtn = "<button type=\"button\" class=\"btn btn-danger btn-xs\"><i class=\" glyphicon glyphicon-remove\"></i></button>";

    var buttonTd = "<td>"+checkBtn+" "+pencilBtn+" "+removeBtn+"</td>"
    var tr = "<tr>"+numberTd+checkboxTd+roleNameTd+buttonTd+"</tr>";

    $("#rolePageBody").append(tr);
  }
  // 生成分页导航条
  generateNavigator(pageInfo);
}

// 生成分页页码导航条
function generateNavigator(pageInfo) {

  // 获取总记录数
  var totalRecord = pageInfo.total;

  // 声明相关属性
  var properties = {
    "num_edge_entries": 3,
    "num_display_entries": 5,
    "callback": paginationCallBack,
    "items_per_page":pageInfo.pageSize,
    "current_page": pageInfo.pageNum - 1,
    "prev_text": "上一页",
    "next_text": "下一页"
  };

  // 调用pagination()函数
  $("#Pagination").pagination(totalRecord, properties);

}

// 翻页时的回调函数
function paginationCallBack(pageIndex,jQuery) {
  // 修改 window 对象的 pageNum 属性
  window.pageNum = pageIndex + 1;

  // 调用分页函数
  generatePage();

  // 取消页码超链接的默认行为
  return false;
}

测试:

在这里插入图片描述

注:如果“上一页”、”下一页“出现乱码,则需要修改Tomcat配置并清楚浏览器缓存。

5 角色信息CRUD

5.1 查询角色信息

修改webui\src\main\webapp\WEB-INF\role-page.jsp

查询按钮功能赋予:

<form class="form-inline" role="form" style="float:left;">
    <div class="form-group has-feedback">
        <div class="input-group">
            <div class="input-group-addon">查询条件</div>
            <input id="keywordInput" class="form-control has-success" type="text" placeholder="请输入查询条件">
        </div>
    </div>
    <button id="searchBtn" type="button" class="btn btn-warning"><i class="glyphicon glyphicon-search"></i> 查询</button>
</form>

响应函数:

<script type="text/javascript">
    $(function (){
        // 1.为分页操作准备初始化数据
        window.pageNum = 1;
        window.pageSize = 5;
        window.keyword = "";

        // 2. 调用分页函数,实现分页效果
        generatePage();

        // 3. 给查询按钮绑定单击响应函数
        $("#searchBtn").click(function (){

            // 获取关键词数据赋值给对应的全局变量
            window.keyword = $("#keywordInput").val();

            // 调用分页函数刷新页面
            generatePage();
        });

    });
</script>

测试:

在这里插入图片描述

5.2 新增角色信息

在webui\src\main\webapp\WEB-INF新增modal-role-add.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<div id="addModal" class="modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">尚筹网系统弹窗</h4>
            </div>
            <div class="modal-body">
                <form class="form-signin" role="form">
                    <div class="form-group has-success has-feedback">
                        <input type="text" name="roleName" class="form-control" placeholder="请输入角色名称" autofocus>
                        <span class="glyphicon glyphicon-user form-control-feedback"></span>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button id="saveRoleBtn" type="button" class="btn btn-primary">保存</button>
            </div>
        </div>
    </div>
</div>

修改webui\src\main\webapp\WEB-INF\role-page.jsp

查询按钮功能赋予:

<button type="button" id="showAddModalBtn" class="btn btn-primary" style="float:right;" ><i class="glyphicon glyphicon-plus"></i> 新增</button>

响应函数:

		// 4. 点击新增按钮打开模态框
        $("#showAddModalBtn").click(function (){
            $("#addModal").modal("show");
        });

        // 5. 给新增模态框中的保存按钮绑定单击响应函数
        $("#saveRoleBtn").click(function (){

            // 获取用户在文本框中输入的角色名称,
            // #addModal 表示找到整个模态框
            // 空格表示在后代元素中继续查找
            // [name=roleName]表示匹配name属性等于roleName的元素
            var roleName = $.trim($("#addModal [name=roleName]").val());

            // 发送ajax请求
            $.ajax({
                url: "role/save.json",
                type: "post",
                data: {
                    roleName: roleName
                },
                dataType: "json",
                success: function (response){
                    let result = response.result;
                    if (result === "SUCCESS") {
                        layer.msg("操作成功!");

                        // 将页码定位到最后一页
                        window.pageNum = 99999999;
                        // 重新加载分页数据
                        generatePage();
                    }
                    if (result === "FAILED") {
                        layer.msg("操作失败!"+response.message);
                    }
                },
                error: function (response) {
                    layer.msg(response.status+""+response.statusText);
                }
            });

        // 关闭模态框
        $("#addModal").modal("hide");

        // 清理模态框
        $("#addModal [name=roleName]").val("");

        });

结尾引入modal-role-add.jsp:

<%@include file="/WEB-INF/modal-role-add.jsp"%>

修改component\src\main\java\com\atguigu\crowd\mvc\handler\RoleHandler.java

@ResponseBody
@RequestMapping("/role/save.json")
public ResultEntity<String> saveRole(Role role) {

    roleService.saveRole(role);

    return ResultEntity.successWithoutData();
}

并新增saverole()方法及实现类:

修改component\src\main\java\com\atguigu\crowd\service\impl\AdminServiceImpl.java

@Override
public void saveRole(Role role) {
    roleMapper.insert(role);
}

测试:

在这里插入图片描述

在这里插入图片描述

5.3 更新角色信息

在webui\src\main\webapp\WEB-INF新增modal-role-edit.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<div id="editModal" class="modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">系统弹窗</h4>
            </div>
            <div class="modal-body">
                <form class="form-signin" role="form">
                    <div class="form-group has-success has-feedback">
                        <input type="text" name="roleName" class="form-control" placeholder="请输入角色名称" autofocus>
                        <span class="glyphicon glyphicon-user form-control-feedback"></span>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button id="updateRoleBtn" type="button" class="btn btn-success">更新</button>
            </div>
        </div>
    </div>
</div>

修改webui\src\main\webapp\WEB-INF\role-page.jsp

响应函数:

// 6.给页面上的“铅笔”按钮绑定单击响应函数,目的是打开模态框
        // 传统的事件绑定方式只能在第一个页面有效,翻页后失效了
        // $(".pencilBtn").click(function(){
        // alert("aaaa...");
        // });
        // 使用 jQuery 对象的 on()函数可以解决上面问题
        // ①首先找到所有“动态生成”的元素所附着的“静态”元素
        // ②on()函数的第一个参数是事件类型
        // ③on()函数的第二个参数是找到真正要绑定事件的元素的选择器
        // ③on()函数的第三个参数是事件的响应函数
        $("#rolePageBody").on("click",".pencilBtn", function (){
            // 打开模态框
            $("#editModal").modal("show");

            // 获取表格中当前行中的角色名称
            var roleName = $(this).parent().prev().text();

            // 获取当前角色id
            window.roleId = this.id;

            // 使用roleName的值设置模态框中的文本框
            $("#editModal [name=roleName]").val(roleName);
        });

        // 7.给更新模态框中的更新按钮绑定单机响应函数
        $("#updateRoleBtn").click(function (){
            // ①从文本框中获取新的角色名称
            var roleName = $("#editModal [name=roleName]").val();

            // ②发送ajax请求执行更新
            $.ajax({
                url: "role/update.html",
                type: "post",
                data: {
                    id: window.roleId,
                    name: roleName
                },
                dataType: "json",
                success: function (response){
                    let result = response.result;
                    if (result === "SUCCESS") {
                        layer.msg("更新成功!");

                        // 重新加载分页数据
                        generatePage();
                    }
                    if (result === "FAILED") {
                        layer.msg("操作失败!"+response.message);
                    }
                },
                error: function (response) {
                    layer.msg(response.status+""+response.statusText);
                }
            });
            // 关闭模态框
            $("#editModal").modal("hide");
        });

结尾引入modal-role-edit.jsp:

<%@include file="/WEB-INF/modal-role-edit.jsp"%>

修改铅笔按钮:webui\src\main\webapp\crowd\my-role.js

// 通过 button 标签的 id 属性(别的属性其实也可以)把 roleId 值传递到 button 按钮的单击 响应函数中,在单击响应函数中使用 this.id
var pencilBtn = "<button id='" + roleId + "'type='button' class='btn btn-primary btn-xs pencilBtn'><i class='glyphicon glyphicon-pencil'></i></button>";

修改component\src\main\java\com\atguigu\crowd\mvc\handler\RoleHandler.java

@ResponseBody
@RequestMapping("/role/update.json")
public ResultEntity<String> updateRole(Role role) {

    roleService.updateRole(role);
    return ResultEntity.successWithoutData();
}

并新增updateRole()方法及实现类:

修改component\src\main\java\com\atguigu\crowd\service\impl\AdminServiceImpl.java

@Override
public void updateRole(Role role) {
    roleMapper.updateByPrimaryKey(role);
}

测试:

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

5.4 删除角色信息

修改component\src\main\java\com\atguigu\crowd\mvc\handler\RoleHandler.java

@ResponseBody
@RequestMapping("/role/remove/by/role/id/array.json")
public ResultEntity<String> removeByRoleIdArray(@RequestBody List<Integer> roleIdList) {

    roleService.removeRole(roleIdList);

    return ResultEntity.successWithoutData();
}

并新增removeRole()方法及实现类:

修改component\src\main\java\com\atguigu\crowd\service\impl\AdminServiceImpl.java

@Override
public void removeRole(List<Integer> roleIdLList) {
    RoleExample example = new RoleExample();

    RoleExample.Criteria criteria = example.createCriteria();

    criteria.andIdIn(roleIdLList);

    roleMapper.deleteByExample(example);
}

在webui\src\main\webapp\WEB-INF新增modal-role-confirm.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<div id="confirmModal" class="modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">系统弹窗</h4>
            </div>
            <div class="modal-body">
                <h4>请确认是否要删除下列角色</h4>
                <div id="roleNameDiv" style="text-align: center;"></div>
            </div>
            <div class="modal-footer">
                <button id="removeRoleBtn" type="button" class="btn btn-primary">确认删除</button>
            </div>
        </div>
    </div>
</div>

修改webui\src\main\webapp\crowd\my-role.js

打开模态框:

// 声明专门的函数,显示确认模态框
function showConfirmModal(roleArray) {

  // 打开模态框
  $("#confirmModal").modal("show");

  // 清除旧数据
  $("#roleNameDiv").empty();

  // 在全局变量范围创建数组用来存放角色 id
  window.roleIdArray = [];

  // 遍历roleArray数组
  for (var i = 0; i < roleArray.length; i++) {
    var role = roleArray[i];
    var roleName = role.roleName;
    $("#roleNameDiv").append(roleName+"<br/>");

    var roleId = role.roleId;

    // 调用数组对象的 push()方法存入新元素
    window.roleIdArray.push(roleId);
  }
}

5.4.1 单个删除

修改删除按钮:webui\src\main\webapp\crowd\my-role.js

var removeBtn = "<button id='" + roleId + "' type=\"button\" class=\"btn btn-danger btn-xs removeBtn\"><i class=\" glyphicon glyphicon-remove\"></i></button>";

修改webui\src\main\webapp\WEB-INF\role-page.jsp

// 8. 点击确认模态框中的确认删除按钮执行删除
        $("#removeRoleBtn").click(function (){

            // 从全局变量范围获取 roleIdArray,转换为 JSON 字符串
            var requestBody = JSON.stringify(window.roleIdArray);
            $.ajax({
                url: "role/remove/by/role/id/array.json",
                type: "post",
                data: requestBody,
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (response){
                    var result = response.result;
                    if (result === "SUCCESS") {
                        layer.msg("操作成功!");

                        // 重新加载分页数据
                        generatePage();
                    }
                    if (result === "FAILED") {
                        layer.msg("操作失败!"+response.message);
                    }
                },
                error: function (response) {
                    layer.msg(response.status+""+response.statusText);
                }
            });
            // 关闭模态框
            $("#confirmModal").modal("hide");
        });

        // 9. 单条删除
        $("#rolePageBody").on("click", ".removeBtn", function (){

            // 从当前按钮出发获取角色名称
            var roleName = $(this).parent().prev().text();

            // 创建role对象存入数组
            var roleArray = [{
                roleId: this.id,
                roleName: roleName
            }];

            // 调用函数打开模态框
            showConfirmModal(roleArray);
        });

结尾引入modal-role-confirm.jsp:

include file="/WEB-INF/modal-role-confirm.jsp"%>

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

5.4.2 全选全不选

修改checkbox:

webui\src\main\webapp\WEB-INF\role-page.jsp

<tr>
    <th width="30">#</th>
    <th width="30"><input id="summaryBox" type="checkbox"></th>
    <th>名称</th>
    <th width="100">操作</th>
</tr>

webui\src\main\webapp\crowd\my-role.js

var checkboxTd = "<td><input class='itemBox' id='" + roleId + "' type='checkbox'></td>";

修改webui\src\main\webapp\WEB-INF\role-page.jsp

// 10.给总的checkbox绑定单击响应函数
        $("#summaryBox").click(function (){

            // ①获取当前多选框自身状态
            var currentStatus = this.checked;

            // ②用当前多选框状态设置其它多选框
            $(".itemBox").prop("checked", currentStatus);
        });

// 11.全选、全不选的反向操作
        $("#rolePageBody").on("click",".itemBox",function (){
            // 获取当前已经选中的.itemBox 的数量
            var checkedBoxCount = $(".itemBox:checked").length;
            // 获取全部.itemBox 的数量
            var totalBoxCount = $(".itemBox").length;
            // 使用二者的比较结果设置总的 checkbox
            $("#summaryBox").prop("checked", checkedBoxCount === totalBoxCount);
        });

测试:

在这里插入图片描述

在这里插入图片描述

5.4.3 批量删除

修改webui\src\main\webapp\WEB-INF\role-page.jsp

        // 12.给批量删除的按钮绑定单击响应函数
        $("#batchRemoveBtn").click(function (){

            // 创建数组对象用来存放后面获取到的角色对象
            var roleArray = [];

            // 遍历当前选中的多选框
            $(".itemBox:checked").each(function (){

                // 使用this引用当前遍历得到的多选框
                var roleId = this.id;

                // 通过DOM操作获取角色名称
                var roleName = $(this).parent().next().text();

                roleArray.push({
                    roleId: roleId,
                    roleName: roleName
                });
            });

            // 检查roleArray的长度是否为0
            if (roleArray.length === 0) {
                layer.msg("请至少选择一个执行删除");
                return;
            }

            // 调用专门的函数打开确认模态框
            showConfirmModal(roleArray);
        });

删除按钮功能赋予:

<button type="button" id="batchRemoveBtn" class="btn btn-danger" style="float:right;margin-left:10px;"><i class=" glyphicon glyphicon-remove"></i> 删除</button>          

测试:

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值