【问题标题】:jQuery code does not work after resetting a div's content twice两次重置 div 的内容后,jQuery 代码不起作用
【发布时间】:2014-11-24 21:04:42
【问题描述】:

有一个div 元素:

...
<div id="liste_secteurs"></div>
...
<script type="text/javascript">
$(document).ready(function() {
     rechercheSecteursEtProduits(0); // setting the div's content 
     $('#btnSupprimer').click(function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
        if ($(':checkbox[id^="prod_"]:checked').length > 0) {
            var msg = "Do you want to remove these records ?";
            if (confirm(msg)) {
                $(':checkbox[id^="prod_"]:checked').each(function(){
                    var type = "",id="";
                    if($(this).val() == "") {   //  delete secteur
                        type = "secteur";
                        var tabIdx = $(this).attr("id").substr(5);
                        id = $("#secteur_"+tabIdx).val();
                    } else {                    //  delete produit
                        type = "produit";
                        id = $(this).val();
                    }
                    $.ajax({
                        data: "type="+type+"&id="+id,
                        type: "POST",
                        url:  "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
                        async: false
                    });
                });
                rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
            }
        }
    });
});

function rechercheSecteursEtProduits(pn){

    var user = "<?php echo $_SESSION[CODE_USER]; ?>";
    var html = $.ajax({
        data: "id_user="+user,
        type: "POST",
        url:  "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
        async: false
    }).responseText;

    $('#liste_secteurs').html(html); // this is the div element

}

</script>

ListerProduitsUserParSecteursAjax.php 代码:

<?php
... // getting database data
?>
<p>Total : <?php echo $nr; ?></p>
<div><a href="service.php?action=ServiceAjouterSecteurProduit"><img src="<?php echo HTTP_ICON.'plus.png'; ?>" /></a></div>
<?php echo $paginationDisplay; ?>
<table id="table" class="data display "  >
  <thead style="background-color:#CCC">
    <tr>
      <th><?php echo _getText("service.produit.form.secteur_activite");?></th>
      <th><?php echo _getText("service.produit.form.titre");?></th>
      <th></th>
      <th><?php if($data["secteur"]["cnt"] > 0){ ?><input type="checkbox" id="check_all"><?php }?></th>
    </tr>
  </thead>
  <tbody style="background-color:#FFF">
    <?php

    if($data["secteur"]["cnt"] > 0){
        for($i=0;$i<$data["secteur"]["cnt"];$i++){?>
    <tr class="odd gradeX">
      <td><?php echo $data["secteur"][$i]["secta_lib_fr"]  ?></td>
      <td><?php echo $data["secteur"][$i]["produit_lib"]  ?></td>
      <td align="center" style="vertical-align:middle"><a href="service.php?action=ServiceModifierSecteurProduit&s=<?php echo $data['secteur'][$i]['id_user_secteur']; ?>&p=<?php echo $data['secteur'][$i]['id_user_produit']; ?>"><img src="<?php echo HTTP_ICON.'edit.png'; ?>" alt="<?php echo _getText('main.btn.modifier'); ?>" style="height:10px;width:10px;" /></a></td>
      <td align="center" style="vertical-align:middle"><input type="checkbox" id="prod_<?php echo $i; ?>" value="<?php echo $data['secteur'][$i]['id_user_produit']; ?>"><input type="hidden" id="secteur_<?php echo $i; ?>" value="<?php echo $data['secteur'][$i]['id_user_secteur']; ?>"></td>
    </tr>
    <?php } ?>
    <?php 
    }
     else{
     ?>
    <tr class="odd gradeX">
      <td colspan="4" align="center"><b><?php echo _getText('main.liste.no_data'); ?></b></td>
    </tr>
    <?php }?>
  </tbody>
</table>
<?php if($data["secteur"]["cnt"] > 0){ ?>
<div align="right"><input name="btnSupprimer" id="btnSupprimer" type="button" value="<?php echo _getText("main.btn.delete"); ?>"   class="btn btn-blue"/></div>
<?php } ?>
<?php echo $paginationDisplay; ?>

当页面第一次加载时,删除按钮可以正常工作:选定的行被删除,并且列表会根据新的数据库数据重新出现。但是后来当我想删除其他行时,当我选中一些复选框并单击删除按钮时,警报不会显示!

那么我的方法有什么问题?

【问题讨论】:

    标签: php jquery html


    【解决方案1】:

    从我正在阅读的内容来看,您遇到了从数据库添加的行的问题。 当您执行这段代码时,可能会出现问题:

    $('#btnSupprimer').click(function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
    

    当您调用 $.click() 函数时,您会将事件添加到所有现有 DOM 对象,其 id 为“btnSupprimer”,但是如果您添加新的 DOM 对象,这不会更新。所以你应该做的是每次添加新行时调用这个函数。你会得到这样的东西:

       function rechercheSecteursEtProduits(pn){
    
            var user = "<?php echo $_SESSION[CODE_USER]; ?>";
            var html = $.ajax({
                data: "id_user="+user,
                type: "POST",
                url:  "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
                async: false
            }).responseText;
    
            $('#liste_secteurs').html(html);
            $('#btnSupprimer').click(addClickHandler()); // this is the div element
    
        }
    
    
    function addClickHandler(){
            if ($(':checkbox[id^="prod_"]:checked').length > 0) {
                var msg = "Do you want to remove these records ?";
                if (confirm(msg)) {
                    $(':checkbox[id^="prod_"]:checked').each(function(){
                        var type = "",id="";
                        if($(this).val() == "") {   //  delete secteur
                            type = "secteur";
                            var tabIdx = $(this).attr("id").substr(5);
                            id = $("#secteur_"+tabIdx).val();
                        } else {                    //  delete produit
                            type = "produit";
                            id = $(this).val();
                        }
                        $.ajax({
                            data: "type="+type+"&id="+id,
                            type: "POST",
                            url:  "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
                            async: false
                        });
                    });
                    rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
                }
            }
        }
    

    希望对你有帮助

    【讨论】:

    • 它接近解决方案!我做了一些修改,请参阅下面的答案:)
    【解决方案2】:

    尝试使用 on 而不是 click 如下

    $('#btnSupprimer').on("click","#liste_secteurs",function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
            if ($(':checkbox[id^="prod_"]:checked').length > 0) {
                var msg = "Do you want to remove these records ?";
                if (confirm(msg)) {
                    $(':checkbox[id^="prod_"]:checked').each(function(){
                        var type = "",id="";
                        if($(this).val() == "") {   //  delete secteur
                            type = "secteur";
                            var tabIdx = $(this).attr("id").substr(5);
                            id = $("#secteur_"+tabIdx).val();
                        } else {                    //  delete produit
                            type = "produit";
                            id = $(this).val();
                        }
                        $.ajax({
                            data: "type="+type+"&id="+id,
                            type: "POST",
                            url:  "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
                            async: false
                        });
                    });
                    rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
                }
            }
        });
    

    【讨论】:

    • 可能是正确的。原因是当您替换div 的内容时,btnSupprimer 被替换为具有相同id 的新元素,该元素没有附加click 事件。 $('#btnSupprimer').on("click") 表示将来添加到页面中的任何名为 btnSupprimer 的内容都将获得附加的点击事件。 $('#btnSupprimer').click() 只是添加到当前实例中,没有其他内容。
    【解决方案3】:

    使用动态 jquery 选择器代替常规的“点击”事件

    $('#liste_secteurs').on('click', '#btnSupprimer', function() {});

    // $("container").on("event", "button", function() {});

    【讨论】:

      【解决方案4】:

      根据 Caveman 的回答,我做了一些更新:

      function rechercheSecteursEtProduits(pn) {
      
          var user = "<?php echo $_SESSION[CODE_USER]; ?>";
          var html = $.ajax({
              data: "id_usermer="+user,
              type: "POST",
              url:  "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
              async: false
          }).responseText;
      
          $('#liste_secteurs').html(html);
          $('#btnSupprimer').on('click',function(){
              if ($(':checkbox[id^="prod_"]:checked').length > 0) {
                  if (confirm("Do you want to remove these records ?")) {
                      $(':checkbox[id^="prod_"]:checked').each(function(){
                          var type = "",id="";
                          if($(this).val() == "") {   //  delete secteur
                              type = "secteur";
                              var tabIdx = $(this).attr("id").substr(5);
                              id = $("#secteur_"+tabIdx).val();
                          } else {                    //  delete produit
                              type = "produit";
                              id = $(this).val();
                          }
                          $.ajax({
                              data: "type="+type+"&id="+id,
                              type: "POST",
                              url:  "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
                              async: false
                          });
                      });
                      rechercheSecteursEtProduits(0);
                  }
              }
          });
      
      }
      

      它有效!

      【讨论】:

        猜你喜欢
        • 2015-05-28
        • 2013-06-12
        • 2013-09-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-14
        • 1970-01-01
        • 2013-07-05
        • 2015-07-22
        相关资源
        最近更新 更多