javascript - jQuery - 如何在从 Ajax 检索数据后添加关闭按钮?

标签 javascript jquery html

我在从 Ajax 检索数据时遇到问题。我想添加按钮“X”以在显示数据后关闭弹出窗口。

我尝试添加一个按钮,例如:

jQuery(".popup").append('<button style="font-size: 150%; color: red; top: 0; right: 0;">x</button>');

在弹出窗口中用户可以关闭我的弹出窗口。

我的代码如下:

function getData(domain){
    var dataString = "domain=" + domain + "&security="+ mhdomain.security + "&action=getdomain" ;
    jQuery.ajax({
        action: "getDomain",
        type: "post",
        url: mhdomain.ajaxurl,
        dataType: "json",
        data: dataString,
        beforeSend: function(xhr){
            jQuery("#wrapper").append('<div class="popup" onclick="popupout(\'.popup\')"></div>');
            jQuery(".popup").append("<img src='https://i.imgur.com/CH8XnNt.gif' alt='loading' />");  
            jQuery(".popup").fadeIn();
            jQuery(".popup").append('<button style="font-size: 150%; color: red; top: 0; right: 0;">x</button>');
        },
        success : function(data){
            jQuery(".popup").html(data.data);
        },
    });      
};
function popupout(popup){
    jQuery(popup).fadeOut(1000);
    jQuery(popup).remove();
}

我的 CSS 代码:

.popup {
    position: fixed;
    display: none;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 99999;
    max-width: 780px;
    width: 100%;
    max-height: 480px;
    height: 100%;
    display: inline-block;
    cursor: pointer;
    background-color: white;
    padding: 30px 50px;
    color: black;
    overflow-y: scroll;
    border: 1px solid #f2f2f2;
}

最佳答案

在您的 beforeSend 事件中,您附加了 html,这很好。但在成功事件中它会被替换。 在这一行中,问题是

jQuery(".popup").html(data.data);

但是您只需在此处附加 data.data 即可解决问题。像这样

jQuery(".popup").append(data.data);

对于评论中的问题,您仍然可以使用 beforeSend 事件。像这样

beforeSend:function(){
// after your codes
jQuery(".popup").append("<img src='loading.gif' class='loading'>");
}

success:function(){
// after your codes
jQuery(".popup").find('.loading').remove();
}

您可以使用 CSS 调整图像的外观。但我分享了如何实现这一目标的想法

关于javascript - jQuery - 如何在从 Ajax 检索数据后添加关闭按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49313392/

相关文章:

javascript - 使用原始查询时,Sequelize 无法识别带有驼峰命名的表

jquery 对话框 .html() 问题

javascript - 当div没有div的id时获取内容...只有类

javascript - Api调用Ajax n秒GET请求

javascript - 如何在浏览器中打印时添加页码

html - 当父容器指定 "vertical-align:middle"时,如何使 "display: table"工作?

javascript - Sequelize 语法错误 (N\')

javascript - 如何编写多个javascript函数?

javascript - 谷歌地图 api v3 未捕获类型错误 : Cannot read property 'offsetWidth' of null

javascript - p2p网络编程