如何在使用JQuery追加HTML元素之后配置它们

How to configure HTML elements after .append-ing them using JQuery?

本文关键字:之后 元素 配置 HTML 追加 JQuery      更新时间:2023-09-26

Noob需要帮助!)在我的代码中,我试图将内容附加到模式窗口,但在附加后,我无法处理元素。JQuery:

$('a[name=modal]').click(function(e) {
    e.preventDefault();
    var id = $(this).attr('href');
    var temp = $(this).attr('id').split('^');
    var modal;
    if (temp[0] == "cat_admin")
    {
        $.ajax({
            type: "POST",
            url:"post.php", 
            data: { message : 'modal_cat_edit' }, 
            success:function(result){
            modal = result;            
            $("#dialog").appendChild(result);
            }
        });
        if ($(this).attr('id') != "c_new") 
        {
            var cid = temp[1];
            var calias = temp[2];
            var cname = temp[3];
            $("#dialog").children("#c_name").val("cname");
            $("#c_alias").val(calias);
            $("#c_id").val(cid);
        }
        else
        {            
            $("#c_name").val('');
            $("#c_alias").val('');
            $("#c_id").val('');
        }

这是附加的HTML:

<input class='n1' type='text' id='c_name' value='' style='width: 350px; border: 1px solid #5C9ACD;' placeholder='Название категории'/>
<input class='n1' type='text' id='c_alias' value='' style='width: 350px; margin-top: 10px; border: 1px solid #5C9ACD;' placeholder='Псевдоним'/>
<input type='hidden' id='c_id' value="">
<div id='c_del' class='det_button' style='float: none; width: 184px; display: inline-block; margin-top: 15px;'>Удалить</div>
<div id='c_save' class='det_button' style='float: none; width: 184px; display: inline-block; margin-top: 15px;'>Сохранить</div>

我犯了什么错?

Javascript不等待AJAX函数完成。它只是继续脚本。

所以把你的

if ($(this).attr('id') != "c_new")

函数转换为AJAX调用中的成功函数

您的问题是ajax请求需要一些时间,并且您试图在实际加载元素之前处理这些元素。

您应该在ajax的success function 中移动jQuery魔术

我想你的Ajaxcall会变慢,只需将你的代码转移到成功恐惧