首页 > 解决方案 > 将 html 附加到 JQUERY AJAX 调用的末尾

问题描述

我正在尝试做某事,经过互联网研究,我不清楚我是否可以。我想在脚本末尾添加模态的 HTML,所有这些都在 AJAX Success 调用中。这可能吗?这是我尝试过的代码:

function options() {
  jQuery.ajax({
    type: 'post',
    url: my_ajax.ajax_url,
    data: {
      action: 'test2_update_function'
    },
    success: function(data) {
      jQuery("#myModal").show(function() {
          // Get the modal
          var modal = document.getElementById("myModal");

          // Get the button that opens the modal
          var btn = document.getElementById("myBtn");

          // Get the <span> element that closes the modal
          var span = document.getElementsByClassName("close")[0];

          // When the user clicks on the button, open the modal
          btn.onclick = function() {
            modal.style.display = "block";
          }

          // When the user clicks on <span> (x), close the modal
          span.onclick = function() {
            modal.style.display = "none";
          }

          // When the user clicks anywhere outside of the modal, close it
          window.onclick = function(event) {
            if (event.target == modal) {
              modal.style.display = "none";
            }
          }
        }
        /*>>> closes the .show*/
      ).append('<div id="myModal" class="modal"><div class="modal-content"><span class="close">&times;</span><p id="my-data"></p></div></div>');
      jQuery("#my-data").html(data); //Add this line
      ;
    }
  });
}

标签: jqueryajaxappend

解决方案


我认为你的意思是这样的

$(function() {
  $("body").append(`<div id="myModal" class="modal">
      <div class="modal-content"><span class="close">&times;</span>
        <p id="my-data"></p>
      </div>
    </div>`); // if you must

  $("#btn").on("click", function() {
    $("#modal").show()
  })

  $("#modal").on("click", ".close", function() {
    $("#modal").hide();
  })

  $(document).on("click", function(e) {
    if ($(e.target).closest("#modal").length === 0 ) {
      $("#modal").hide()
    }
  })
})

function options() {
  $.ajax({
    type: 'post',
    url: my_ajax.ajax_url,
    data: {
      action: 'test2_update_function'
    },
    success: function(data) {
      $("#my-data").html(data); //Add this line
      $("#myModal").show()

    }
  });
}
<div id="myModal" class="modal">
  <div class="modal-content"><span class="close">&times;</span>
    <p id="my-data"></p>
  </div>
</div>

推荐阅读