jQuery创建具有ID的新div?

Joh*_*ohn 1 html asp.net ajax jquery

我在ASP.NET masterPage.master中有表单,如果我单击“提交”,则通过ajax从masterPage.master.cs文件调用某种方法(我在更新面板中有此方法)。但是我想用jQuery改善它。所以我有这个:

$('#submit').click(function () {
            $.ajax({
                type: "POST",
                url: '<% Response.Write("~"+Request.Path); %>',
                beforeSend: function () {
                    $(document.createElement('div')).width($('#formBox').width())
                    .height($('#formBox').height())
                    .css({ backgroundImage: 'url(/Static/Img/bc_overlay.png)', position: 'absolute', left: 0, top: 0, margin: "5px", textAlign: "center", color: "#000", display: "none" })
                    .append("<strong>Na?ítám</strong><br /><img src='Static/Img/ajax-loader.gif' width='33px' height='33px' alt='loading' />")
                    .fadeIn("slow")
                    .prependTo($('#formBox'));
                    $('#formBox').css('position', 'relative');
                },
                success: function () {
                }
            });
        });
Run Code Online (Sandbox Code Playgroud)

因此,如果我单击“提交”,则会创建新的div(正在加载文本和图像,以及很酷的不透明度覆盖层),但是我如何给该div一些ID?因为我需要在

success: function () {
                    }
Run Code Online (Sandbox Code Playgroud)

我需要清除此框并在此处输入一些文字(错误或成功)。

Sam*_*nes 6

我喜欢以这种方式创建元素:

    $('<div/>',{
        id: 'idhere',
        css:{
            width: $('#formBox').width(),
            height: $('#formBox').height()
        }
    });
Run Code Online (Sandbox Code Playgroud)

等等...

作为参考 - 一些属性具有保留字/名称(请参阅MDN 保留字),因此如果您想指定一个类,您需要包装属性名称:

        $('<div/>',{
            id: 'idhere',
            'class':'myclassname',
            css:{
                width: $('#formBox').width(),
                height: $('#formBox').height()
            }
        });
Run Code Online (Sandbox Code Playgroud)

您当然可以为这个新元素指定一个名称,并在进行过程中对其进行更改...

var div = $('<div/>',{
                id: 'idhere',
                'class':'myclassname',
                css:{
                    width: $('#formBox').width(),
                    height: $('#formBox').height()
                }
            });

$(div).prop('name','saymyname');
Run Code Online (Sandbox Code Playgroud)

  • 有关保留关键字的信息非常有帮助! (2认同)

Joh*_*hnP 5

只需在创建属性时进行设置

$(document.createElement('div')).attr('id', 'theID')//rest of code
Run Code Online (Sandbox Code Playgroud)