jquery append div inside div with id and manipulate

后端 未结 4 963
轻奢々
轻奢々 2021-02-04 00:08

after 2 hours of searching I decided to ask my question.

I have a div:

I want to add a div inside th

相关标签:
4条回答
  • 2021-02-04 00:37

    It's just the wrong order

    var e = $('<div style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
    $('#box').append(e);    
    e.attr('id', 'myid');
    

    Append first and then access/set attr.

    0 讨论(0)
  • 2021-02-04 00:39

    You're overcomplicating things:

    var e = $('<div style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
    e.attr('id', 'myid');
    $('#box').append(e);
    

    For example: http://jsfiddle.net/ambiguous/Dm5J2/

    0 讨论(0)
  • 2021-02-04 00:41

    Why not go even simpler with either one of these options:

    $("#box").html('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
    

    Or, if you want to append it to existing content:

    $("#box").append('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
    

    Note: I put the id="myid" right into the HTML string rather than using separate code to set it.

    Both the .html() and .append() jQuery methods can take a string of HTML so there's no need to use a separate step for creating the objects.

    0 讨论(0)
  • 2021-02-04 00:52
    var e = $('<div style="display:block; id="myid" float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
    $("#box").html(e);
    
    0 讨论(0)
提交回复
热议问题