在附加元素中附加元素在jQuery中不起作用

Posted

技术标签:

【中文标题】在附加元素中附加元素在jQuery中不起作用【英文标题】:Appending element inside appended element not working in jQuery 【发布时间】:2020-09-11 04:12:22 【问题描述】:

我正在制作一个更改密码模块,其中单击编辑密码按钮会显示一个模式,其中旧/当前密码表单被附加到模式正文中,用户必须在输入正确密码时插入他的当前密码,新密码表单被附加到模态正文。单击新密码提交按钮时,它的第一项工作是检查密码的长度是否小于 7 个字符,如果它是真的,带有消息的跨度会附加到新密码表单的提交按钮 id。但它不会将 span 元素附加到已附加的元素,即新密码表单。

我是 jquery/Laravel 的新手,不知道为什么这不起作用。

$(document).ready(function()
        function show_old_password_modal()
            $("#editModal").show();
            $("#modalBody , .modal-title").html("");
            $(".modal-title").append("Enter Old Password");
            $("#modalBody").append("<form method='POST'>"+
                                        "<div class='form-inline'>"+
                                            "<label for='oldPassword'>Old Password: </label> &nbsp;&nbsp;"+
                                            "<input type='password' id='oldPassword' class='form-control col-lg-6'>"+
                                        "</div> "+
                                        "<br>"+
                                        "<span class='badge badge-danger' id='spanDanger' ></span>"+ 
                                        "<br>"+
                                        "<input type='submit' id='oldPasswordSubmit' class='btn btn-success update-btn' value='Submit'> "+
                                    "</form>");
        

        $("#edit-password").click(function()
            show_old_password_modal();
        );

        $(document).on("click","#oldPasswordSubmit", function(e)
            e.preventDefault();
            var userId = " Auth::user()->id ";
            console.log(userId);
            var oldPassword = $("#oldPassword").val();
            console.log(oldPassword);
            $.ajaxSetup(
                headers: 
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                
            );
            $.ajax(
                url: " route('check.old.password') ",
                message: "GET",
                data:  userId : userId , oldPassword : oldPassword ,
                success: function(data)
                    console.log(data.result);
                    if(data.result == 1)
                        $("#modalBody , .modal-title").html("");
                        $(".modal-title").append("Enter New Password");
                        $("#modalBody").append("<form method='POST'>"+
                                                    "<div class='form-inline'>"+
                                                        "<label for='newPassword'>New Password: </label> &nbsp;&nbsp;"+
                                                        "<input type='password' id='newPassword' class='form-control col-lg-6'>"+
                                                    "</div> "+
                                                    "<br>"+
                                                    "<input type='submit' id='newPasswordSubmit' class='btn btn-success update-btn' value='Submit'> "+ 
                                                "</form>");
                    
                    else
                        show_old_password_modal();
                        $("#spanDanger").text("Invalid Old Password");
                        
                ,
                error: function(error)
                    console.log(error.responseText);
                
            );
        );

        $(document).on("click","#newPasswordSubmit",function(e)
            e.preventDefault();
            var userId = " Auth::id() "
            console.log("userId: "+userId);
            var newPassword = $("#newPassword").val();
            console.log("newPass: "+newPassword);
            if(newPassword.length < 7)
                //$("#spanA").html("Password length should be greater than 6");
                $("#newPasswordSubmit").append("<span class='badge badge-danger'>Password length should be greater than 6</span>");
                return;
            
            $.ajaxSetup(
                headers: 
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                
            );
            $.ajax(
                url: " url('/editProfile/password?_method=PUT') ",
                method: "POST",
                data:  userId : userId , newPassword : newPassword ,
                success: function(data)
                    console.log(data);
                    $("#editModal").hide();
                    message(data.message , data.status);
                ,
                error: function(error)
                    console.log(error.responseText);
                
            );
        );

            $("#closeModal").click(function()
                $("#editModal").hide();
            );
        
    );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<div class="container-fluid">
        <div class="modal" id="editModal">
            <div class="modal-dialog">
              <div class="modal-content">
          
                <!-- Modal Header -->
                <div class="modal-header">
                  <h4 class="modal-title"></h4>
                  <button type="button" class="close" id="closeModal" data-dismiss="modal">&times;</button>
                </div>
          
                <!-- Modal body -->
                <div class="modal-body" id="modalBody">
                  
                </div>
          
              </div>
            </div>
        </div>
    </div>
    <div class="container">
        <div class="row">
            <h1 class="col-lg-6 text-center">Profile</h1>
        </div>
        <div class="row">
            <div class="card col-lg-6">
                <div class="card-body">
                    <div class="name">
                        <label for="name">Name: </label>
                        <b id="showName"></b>
                        <a type="button" id="edit-name" class="btn btn-primary btn-sm float-right">Edit</a>
                    </div>
                    <hr>
                    <div class="email">
                        <label for="email">Email: </label>
                        <b id="showEmail"></b>
                        <a type="button" id="edit-email" class="btn btn-primary btn-sm float-right">Edit</a>
                    </div>
                    <hr>
                    <div class="password">
                        <label for="passsword">Password: </label>
                        <b>*********</b>
                        <a type="button" id="edit-password" class="btn btn-primary btn-sm float-right">Edit</a>
                    </div>
                </div>
            </div>
            <div class="card offset-lg-2 col-lg-4 h-25" id="message">
                <div class="card-body" id="msgCardBody">

                </div>
            </div>
        </div>
    </div>

【问题讨论】:

【参考方案1】:

在您的代码中,您将错误消息附加到输入框,这是不可能的。您可以将 span 附加到某个 div 即:&lt;div class='newPasswordSubmit'&gt;&lt;/div&gt; 此处使用 $(".newPasswordSubmit").html.. 将在您的输入框下方附加您的错误消息。

演示代码(我已经删除了 ajax 代码和一些其他代码):

$(document).ready(function() 
  function show_old_password_modal() 
    $("#editModal").show();
    $("#modalBody , .modal-title").html("");
    $(".modal-title").append("Enter Old Password");
    $("#modalBody").append("<form method='POST'>" +
      "<div class='form-inline'>" +
      "<label for='oldPassword'>Old Password: </label> &nbsp;&nbsp;" +
      "<input type='password' id='oldPassword' class='form-control col-lg-6'>" +
      "</div> " +
      "<br>" +
      "<span class='badge badge-danger' id='spanDanger' ></span>" +
      "<br>" +
      "<input type='submit' id='oldPasswordSubmit' class='btn btn-success update-btn' value='Submit'> " +
      "</form>");
  

  $("#edit-password").click(function() 
    show_old_password_modal();
  );

  $(document).on("click", "#oldPasswordSubmit", function(e) 
    e.preventDefault();
    var userId = " Auth::user()->id ";
    console.log(userId);
    var oldPassword = $("#oldPassword").val();
    console.log(oldPassword);
 
          $("#modalBody , .modal-title").html("");
          $(".modal-title").append("Enter New Password");
          $("#modalBody").append("<form method='POST'>" +
            "<div class='form-inline'>" +
            "<label for='newPassword'>New Password: </label> &nbsp;&nbsp;" +
            "<input type='password' id='newPassword' class='form-control col-lg-6'>" +
            "</div> " +
            "<br>" +
            "<input type='submit' id='newPasswordSubmit' class='btn btn-success update-btn' value='Submit'> <div class='newPasswordSubmit'></div>" +
            "</form>"); //<--adding <div></div>
       
  );

  $(document).on("click", "#newPasswordSubmit", function(e) 
    e.preventDefault();
    var userId = " Auth::id() "
    console.log("userId: " + userId);
    var newPassword = $("#newPassword").val();
    console.log("newPass: " + newPassword);
    if (newPassword.length < 7) 
      //$("#spanA").html("Password length should be greater than 6");
    //change to class
      $(".newPasswordSubmit").html("<span class='badge badge-danger'>Password length should be greater than 6</span>");
      return;
    else
      $(".newPasswordSubmit").html('');//remove span if condtion false
   console.log("go done")
   
  );

  $("#closeModal").click(function() 
    $("#editModal").hide();
  );

);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<div class="container-fluid">
  <div class="modal" id="editModal">
    <div class="modal-dialog">
      <div class="modal-content">

        <!-- Modal Header -->
        <div class="modal-header">
          <h4 class="modal-title"></h4>
          <button type="button" class="close" id="closeModal" data-dismiss="modal">&times;</button>
        </div>

        <!-- Modal body -->
        <div class="modal-body" id="modalBody">

        </div>

      </div>
    </div>
  </div>
</div>
<div class="container">
  <div class="row">
    <h1 class="col-lg-6 text-center">Profile</h1>
  </div>
  <div class="row">
    <div class="card col-lg-6">
      <div class="card-body">
        <div class="name">
          <label for="name">Name: </label>
          <b id="showName"></b>
          <a type="button" id="edit-name" class="btn btn-primary btn-sm float-right">Edit</a>
        </div>
        <hr>
        <div class="email">
          <label for="email">Email: </label>
          <b id="showEmail"></b>
          <a type="button" id="edit-email" class="btn btn-primary btn-sm float-right">Edit</a>
        </div>
        <hr>
        <div class="password">
          <label for="passsword">Password: </label>
          <b>*********</b>
          <a type="button" id="edit-password" class="btn btn-primary btn-sm float-right">Edit</a>
        </div>
      </div>
    </div>
    <div class="card offset-lg-2 col-lg-4 h-25" id="message">
      <div class="card-body" id="msgCardBody">

      </div>
    </div>
  </div>
</div>

【讨论】:

即使我尝试过并且成功了,但我最初的问题是为什么不能将带有文本属性的整个 span/div 标签附加到已经附加的元素中。在我的情况下,带有输入字段和提交按钮的新密码表单附加在 modal-body 中,那么为什么我不能在它下面附加一个新的 div/span 元素呢? 因为当您使用附加元素时,您正在附加的元素中添加一些其他元素。在您的代码中,您将 span 附加到您的 input 即:&lt;input..&gt;&lt;span&gt;..&lt;/input&gt; div,p,h1.. 等。查看有关append 的更多信息。 好吧,你的意思是跨度被附加到输入,即 .. 。但是 append() 方法会在所选元素的末尾插入指定的内容,所以这里它是如何在输入标签之间结束的? 它将指定的内容附加为每个元素的最后一个子元素。请阅读该页面以获取有关append方法的更多信息。【参考方案2】:

$(document).ready(function()
        function show_old_password_modal()
            $("#editModal").show();
            $("#modalBody , .modal-title").html("");
            $(".modal-title").append("Enter Old Password");
            $("#modalBody").append("<form method='POST'>"+
                                        "<div class='form-inline'>"+
                                            "<label for='oldPassword'>Old Password: </label> &nbsp;&nbsp;"+
                                            "<input type='password' id='oldPassword' class='form-control col-lg-6'>"+
                                        "</div> "+
                                        "<br>"+
                                        "<span class='badge badge-danger' id='spanDanger' ></span>"+ 
                                        "<br>"+
                                        "<input type='submit' id='oldPasswordSubmit' class='btn btn-success update-btn' value='Submit'> "+
                                    "</form>");
        

        $("#edit-password").click(function()
            show_old_password_modal();
        );

        $(document).on("click","#oldPasswordSubmit", function(e)
            e.preventDefault();
            var userId = " Auth::user()->id ";
            console.log(userId);
            var oldPassword = $("#oldPassword").val();
            console.log(oldPassword.length); 
            $("#oldPasswordSubmit").parent().find('.badge').remove(); 
                        if(oldPassword.length < 7)
                //$("#spanA").html("Password length should be greater than 6");               
                $("#oldPasswordSubmit").after("<span class='badge badge-danger'>Password length should be greater than 6</span>");
                return;
            
            $.ajaxSetup(
                headers: 
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                
            );
            $.ajax(
                url: " route('check.old.password') ",
                message: "GET",
                data:  userId : userId , oldPassword : oldPassword ,
                success: function(data)
                    console.log(data.result);
                    if(data.result == 1)
                        $("#modalBody , .modal-title").html("");
                        $(".modal-title").append("Enter New Password");
                        $("#modalBody").append("<form method='POST'>"+
                                                    "<div class='form-inline'>"+
                                                        "<label for='newPassword'>New Password: </label> &nbsp;&nbsp;"+
                                                        "<input type='password' id='newPassword' class='form-control col-lg-6'>"+
                                                    "</div> "+
                                                    "<br>"+
                                                    "<input type='submit' id='newPasswordSubmit' class='btn btn-success update-btn' value='Submit'> "+ 
                                                "</form>");
                    
                    else
                        show_old_password_modal();
                        $("#spanDanger").text("Invalid Old Password");
                        
                ,
                error: function(error)
                    console.log(error.responseText);
                
            );
        );

        $(document).on("click","#newPasswordSubmit",function(e)
            e.preventDefault();
            var userId = " Auth::id() "
            console.log("userId: "+userId);
            var newPassword = $("#newPassword").val();
            console.log("newPass: "+newPassword.length);
            if(newPassword.length < 7)
                //$("#spanA").html("Password length should be greater than 6");
                $("#newPasswordSubmit").append("<span class='badge badge-danger'>Password length should be greater than 6</span>");
                return;
            
            $.ajaxSetup(
                headers: 
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                
            );
            $.ajax(
                url: " url('/editProfile/password?_method=PUT') ",
                method: "POST",
                data:  userId : userId , newPassword : newPassword ,
                success: function(data)
                    console.log(data);
                    $("#editModal").hide();
                    message(data.message , data.status);
                ,
                error: function(error)
                    console.log(error.responseText);
                
            );
        );

            $("#closeModal").click(function()
                $("#editModal").hide();
            );

    );
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<!-- Latest compiled javascript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="container-fluid">
        <div class="modal" id="editModal">
            <div class="modal-dialog">
              <div class="modal-content">

                <!-- Modal Header -->
                <div class="modal-header">
                  <h4 class="modal-title"></h4>
                  <button type="button" class="close" id="closeModal" data-dismiss="modal">&times;</button>
                </div>

                <!-- Modal body -->
                <div class="modal-body" id="modalBody">

                </div>

              </div>
            </div>
        </div>
    </div>
    <div class="container">
        <div class="row">
            <h1 class="col-lg-6 text-center">Profile</h1>
        </div>
        <div class="row">
            <div class="card col-lg-6">
                <div class="card-body">
                    <div class="name">
                        <label for="name">Name: </label>
                        <b id="showName"></b>
                        <a type="button" id="edit-name" class="btn btn-primary btn-sm float-right">Edit</a>
                    </div>
                    <hr>
                    <div class="email">
                        <label for="email">Email: </label>
                        <b id="showEmail"></b>
                        <a type="button" id="edit-email" class="btn btn-primary btn-sm float-right">Edit</a>
                    </div>
                    <hr>
                    <div class="password">
                        <label for="passsword">Password: </label>
                        <b>*********</b>
                        <a type="button" id="edit-password" class="btn btn-primary btn-sm float-right">Edit</a>
                    </div>
                </div>
            </div>
            <div class="card offset-lg-2 col-lg-4 h-25" id="message">
                <div class="card-body" id="msgCardBody">

                </div>
            </div>
        </div>
    </div>

【讨论】:

以上是关于在附加元素中附加元素在jQuery中不起作用的主要内容,如果未能解决你的问题,请参考以下文章

具有动态内容的动态附加 iframe 在内容元素上写入 jquery 事件句柄不起作用

禁用日期的 HTML5 日期选择器在 Angular 中不起作用

jQuery Datepicker 在动态元素中不起作用

附加函数在调整大小的数组中不起作用

允许其他受保护的附加在 Azure 流分析中不起作用?

附加 DOM 元素不适用于 jQuery 可选