jQuery create new div with ID?

后端 未结 4 439
栀梦
栀梦 2021-01-22 03:29

I have form in my ASP.NET masterPage.master and if i click on submit it call some method from masterPage.master.cs file by ajax (i have it in update panel). But i want improve i

相关标签:
4条回答
  • 2021-01-22 03:46

    All the answers are valid.

    Another way:

    HTML

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

    JQuery

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

    Or:

     $('#container').append(createDiv('id', 'class'));
    
     var createDiv = function(newid, newclass) {
        return $('<div/>', {
                  id: newid,
                  class: newclass,
                  css:{
                     width: "100px",
                     height: "100px"
                  }
                });
     } 
    
    0 讨论(0)
  • 2021-01-22 04:05

    Just set the attribute when you're creating it

    $(document.createElement('div')).attr('id', 'theID')//rest of code
    
    0 讨论(0)
  • 2021-01-22 04:08

    I like to create the element this way:

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

    etc...

    For reference - some attributes have reserved words/names (see MDN Reserved Words), so if you wanted to specify a class you need to wrap the attribute name:

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

    You can of course assign a name to this new element and change it as you go along...

    var div = $('<div/>',{
                    id: 'idhere',
                    'class':'myclassname',
                    css:{
                        width: $('#formBox').width(),
                        height: $('#formBox').height()
                    }
                });
    
    $(div).prop('name','saymyname');
    
    0 讨论(0)
  • 2021-01-22 04:09

    I did not quite get the setup you have created.

    The success function is actually called with 3 parameters.

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

    You can safely ignore textStatus and jqXHR and just write

    success : function( data ) {
    }
    

    The data element is the result you get back from you ajax call. You can search within that data to get the desired ID.

    Another option would be to create the div from jQuery with a simple insert or append call and create the id in the script. (perhaps using date and time to be unique, or just get the highest id and increase a counter) You could then just load the html to be placed into the div via a call to jquery.

    0 讨论(0)
提交回复
热议问题