>  기사  >  웹 프론트엔드  >  jQuery의 체크박스 즉시 수정 및 일괄 삭제 기능 구현을 설명하는 예

jQuery의 체크박스 즉시 수정 및 일괄 삭제 기능 구현을 설명하는 예

小云云
小云云원래의
2017-12-22 10:28:351979검색

이 글은 주로 jQuery의 체크박스 즉시 수정 및 일괄 삭제 구현과 그 과정에서 직면하게 되는 함정을 소개합니다. 매우 훌륭하고 참고할 가치가 있습니다. 모두가 jQuery를 더 잘 배우고 익히는 데 도움이 되기를 바랍니다. .

최근에 jQuery를 사용하여 일괄 삭제 작업을 구현했습니다. 그 효과는 아래와 같습니다

이 페이지에서는 다운로드할 필요가 없는 경우에는 부트스트랩과 jQuery를 사용합니다.

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title>视频管理</title>
  <link rel="stylesheet" type="text/css" href="css/init.css" rel="external nofollow" />
  <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" rel="external nofollow" />
  <script src="js/jquery-3.2.1.min.js"></script>
  <script src="js/bootstrap.min.js"></script>
  <style type="text/css">
   .head {
    background-color: #EFEFF4;
    font-size: 16px;
    color: black;
    padding: 20px;
    font-size: 20px;
    overflow: hidden;
    margin-bottom: 10px;
   }
   .table {
    margin-top: 30px;
    border: 1px solid #CCCCCC;
   }
   .name_info {
    color: red;
   }
   .message p {
    margin: 0px;
    padding: 0px;
   }
   .form_0 {
    background-color: #EEEEEE;
   }
  </style>
 </head>
 <body>
  <p class="container-fluid">
   <p id="row" class="head">
    <p class="col-sm-12 col-md-12 col-lg-12">
     <p>视频管理</p>
    </p>
   </p>
   <p id="row" class="col-sm-12 col-md-12">
    <p class="col-xs-1">
     <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="batchDel" class="btn btn-danger btn">批量删除 <span class="badge" id="badge_0">0</span></a>
    </p>
    <p class="col-xs-1">
     <p class="text-danger">删除成功</p>
    </p>
    <p class="col-xs-1">
     <a href="speaker_add.html" rel="external nofollow" class="btn btn-primary btn">添加</a>
    </p>
    <p id="row" class="col-xs-6 col-md-offset-1">
     <form class="form-inline form_0" role="form">
      <p class="form-group col-xs-3 col-md-3">
       <input type="text" class="form-control" id="name" placeholder="课程名称">
      </p>
      <p class="form-group col-xs-2 col-md-2">
       <select class="form-control btn-primary">
        <option>请选择课程</option>
        <option>2</option>
       </select>
      </p>
      <p class="form-group col-xs-2 col-md-2">
       <select class="form-control btn-primary">
        <option>请选择老师</option>
        <option>2</option>
       </select>
      </p>
      <p class="form-group col-xs-2 col-md-2">
       <button type="submit" class="btn btn-primary">查询</button>
      </p>
     </form>
    </p>
   </p>
   <p class="row">
    <p class="col-md-10 col-lg-10">
     <table class="table table-striped">
      <thead>
       <tr>
        <th>选择</th>
        <th>序号</th>
        <th>名称</th>
        <th>介绍</th>
        <th>讲师</th>
        <th>时长</th>
        <th>播放次数</th>
        <th>编辑</th>
        <th>删除</th>
       </tr>
      </thead>
      <tbody>
       <tr>
        <td>
         <input class="check_0" value="0" type="checkbox">
        </td>
        <td class="show_id">1</td>
        <td id="show_name">环境搭建</td>
        <td>这视频真tm牛逼</td>
        <td>老王</td>
        <td>666</td>
        <td>666</td>
        <td>
         <a href="video_update.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="edit_submit"><span class="glyphicon glyphicon-pencil"></span>编辑</a>
        </td>
        <td>
         <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="delete" data-toggle="modal" data-target="#myModal"><span class="glyphicon glyphicon-trash"></span>删除</a>
        </td>
       </tr>
       <tr>
        <td>
         <input class="check_0" value="1" type="checkbox">
        </td>
        <td class="show_id">1</td>
        <td id="show_name">环境搭建</td>
        <td>这视频真tm牛逼</td>
        <td>老王</td>
        <td>666</td>
        <td>666</td>
        <td>
         <a href="video_update.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="edit_submit"><span class="glyphicon glyphicon-pencil"></span>编辑</a>
        </td>
        <td>
         <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="delete" data-toggle="modal" data-target="#myModal"><span class="glyphicon glyphicon-trash"></span>删除</a>
        </td>
       </tr>
       <tr>
        <td>
         <input class="check_0" value="2" type="checkbox">
        </td>
        <td class="show_id">1</td>
        <td id="show_name">环境搭建</td>
        <td>这视频真tm牛逼</td>
        <td>老王</td>
        <td>666</td>
        <td>666</td>
        <td>
         <a href="video_update.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="edit_submit"><span class="glyphicon glyphicon-pencil"></span>编辑</a>
        </td>
        <td>
         <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="delete" data-toggle="modal" data-target="#myModal"><span class="glyphicon glyphicon-trash"></span>删除</a>
        </td>
       </tr>
      </tbody>
     </table>
    </p>
   </p>
   <p class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <p class="modal-dialog">
     <p class="modal-content">
      <p class="modal-header">
       <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
       <h4 class="modal-title" id="myModalLabel">温馨提示</h4>
      </p>
      <p id="info" class="modal-body">你确定要删除吗?</p>
      <p class="modal-footer">
       <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
       <button type="button" id="delete_submit" class="btn btn-primary">确定</button>
      </p>
     </p>
     <!-- /.modal-content -->
    </p>
    <!-- /.modal -->
   </p>
  </p>
  <form id="form" method="post">
   <input type="hidden" name="_method" id="_method" value="DELETE" />
   <input type="hidden" name="id" id="id" />
  </form>
 </body>
 <script type="text/javascript">
  $(document).ready(function() {
   $("#delete").click(function() {
    var click_name = $(this).parent().siblings("#show_name").html();
    var click_id = $(this).parent().siblings("#show_id").html();
    $("#info").html("你确定要删除视频:<a class=&#39;name_info&#39;>" + click_name + "</a>吗?");
    $("#id").val(click_id);
   })
   $("#delete_submit").click(function() {
    $("#_method").val("DELETE");
    $("#form").submit();
   })
   $("#edit_submit").click(function() {
    var click_id = $(this).parent().siblings("#show_id").html();
    $("#id").val(click_id);
    $("#form").attr("method", "get");
    $("#_method").val("get");
    $("#form").submit();
   })
   //获取选中的个数
   $(".check_0").click(function() {
    $("#badge_0").html($("input[type=checkbox]:checked").length);
    //alert($("input[type = checkbox]: checked ").length); 
   })
   //批量删除
   $("#batchDel").click(function() {
     var params = "";
     $("input[type = checkbox]:checked").each(function(index,element){
      //第一个id不需要加前缀
      if(index == 0) {
       params += "id=" +
        $(this).val();
      } else {
       params += "&id=" +
        $(this).val();
      }
     });
     alert("生成的拼接参数:" + params);
   })
  })
 </script>
</html>


위 그림의 작업은 주로 두 가지 작업이 필요합니다:

1. 체크박스를 클릭하면 선택 항목이 계산됩니다(함정 포함).

2. 일괄 삭제를 클릭하면 선택한 유닛의 ID가 스플라이싱되어 백그라운드로 전달됩니다.

언뜻 보면 구현하기 쉽고 구현 방법이 다양하다는 느낌이 듭니다. 저도 처음에는 그렇게 생각했는데 오전 내내 시간을 보냈네요... 다음으로 jQuery의 함정 몇 가지를 살펴보겠습니다.

내 초기 아이디어는 체크박스를 클릭할 때마다 모든 체크박스에 대해 각각() 순회를 수행하는 것입니다. 체크된 경우 Num++를 추가하고 마지막으로 일괄 삭제를 위해 작은 디지털 태그에 num 값을 할당합니다. ID도 연결되어 있습니다.

$(".check_0").click(function(){
     var num=0;
    var del_str="";
    $(".check_0").each(function(){
     alert($(this).val()+":"+$(this).attr("checked"));
     if($(this).attr("checked")=="checked"){
      num++;
      del_str+=$(this).parent().siblings("show_id").html()+"/";
     }
     alert(this.checked);
    })
   })

이 코드가 실행되었을 때 이상한 현상이 발견되었습니다. 효과가 확인되기 전에 이 코드가 실행되었습니다. beforeClick()과 유사하므로 코드를 순회할 때 현재 확인 상태를 얻을 수 없습니다.

이 문제에 대해 오랫동안 인터넷에서 답변을 찾았지만 해결 방법을 몰랐습니다. mouseup() 메소드를 모두 시도했지만 모두 beforeClick의 효과가 있었습니다.

드디어 다른 글쓰기 방법을 사용했어요.

//获取选中的个数
   $(".check_0").click(function() {
    $("#badge_0").html($("input[type=checkbox]:checked").length);
    //alert($("input[type = checkbox]: checked ").length); 
   })
   //批量删除
   $("#batchDel").click(function() {
     var params = "";
     $("input[type = checkbox]:checked").each(function(index,element){
      //第一个id不需要加前缀
      if(index == 0) {
       params += "id=" +
        $(this).val();
      } else {
       params += "&id=" +
        $(this).val();
      }
     });
     alert("生成的拼接参数:" + params);
   })

  성공적으로 작동했습니다!

결론:

확인된 요소를 가져오기 위해 click()에서

선택기를 사용하면 click() 후에 확인된 결과를 얻게 됩니다.

 .each()를 사용하여 순회하면 클릭하기 전에 효과를 얻을 수 있습니다. input[type=[checkbox]:checked]

  왜 클릭 기능에서 beforeclick과 aferclick의 두 가지 효과가 있을 수 있나요?

관련 권장 사항:

jQuery는 검색 기능을 구현하고 검색 관련 내용을 표시합니다.

jQuery에 대한 자세한 설명 지정된 영역을 제외한 아무 곳이나 클릭하면 DIV 기능이 숨겨집니다.

실용적 간단한 작업에 대한 자세한 설명 예 체크박스를 구현하는 jQuery

위 내용은 jQuery의 체크박스 즉시 수정 및 일괄 삭제 기능 구현을 설명하는 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.