2011-03-15 99 views
1

我有我的ASP.NET masterPage.master形式,如果我点击提交从ajax调用masterPage.master.cs文件(我有更新面板)中的某些方法。但我想用jQuery改进它。所以我有这样的:jQuery使用ID创建新的div?

$('#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() { 
       } 
      }); 
     }); 

所以,如果我点击提交,新的div正在创造(有加载的文字和图片,以及酷不透明覆盖),但是我怎么给这个div身份证吗?因为我需要在

success: function() { 
        } 

使用它,我需要清除该复选框,并在这里写一些文字(错误或成功)。

回答

4

当你创建它

$(document.createElement('div')).attr('id', 'theID')//rest of code 
+0

这就是我需要的,thx :-) – John 2011-03-15 17:12:04

+0

欢迎来到SO!如果这解决了您的问题,请将问题标记为“已回答”,这样可以帮助其他人。使用左侧的大勾号标记:http://stackoverflow.com/faq#howtoask – JohnP 2011-03-15 17:17:21

0

我并没有完全得到你所创建的设置只需设置属性。

成功函数实际上是用3个参数调用的。

success : function(data, textStatus, jqXHR) { 
} 

您可以放心地忽略textStatus和jqXHR和只写

success : function(data) { 
} 

数据元素是你从你的AJAX调用回结果。 您可以在该数据中搜索以获取所需的ID。

另一种选择是通过简单的插入或追加调用从jQuery创建div,并在脚本中创建id。 (也许使用日期和时间是唯一的,或者只是获得最高的ID并增加计数器) 然后,您可以通过调用jquery来加载要放入div的html。

3

我喜欢创造的元素是这样的:

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

等等

仅供参考 - 某些属性有保留字/名称(见MDN Reserved Words),所以如果你想指定类,你需要包装的属性名称:

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

当然你也可以指定一个名称这个新元素,并改变它,你走......

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

$(div).prop('name','saymyname'); 
+0

有关保留关键字的信息非常有帮助! – tyranitar 2015-02-13 14:32:52

0

所有的答案都是有效的。

另一种方式:

HTML

<div id='container'></div> 

JQuery的

$('#container').append("<div id=\"id\"></div>"); 

或者:

$('#container').append(createDiv('id', 'class')); 

var createDiv = function(newid, newclass) { 
    return $('<div/>', { 
       id: newid, 
       class: newclass, 
       css:{ 
       width: "100px", 
       height: "100px" 
       } 
      }); 
}