开发者

Is this the right way to setup up an image within a link?

开发者 https://www.devze.com 2023-01-02 03:54 出处:网络
$(\'<a />\').attr({ \'href\': \'#\' }) .append( 开发者_运维问答$(\'<img />\').attr({ \'id\': \'img\',
    $('<a />').attr({
        'href': '#'
    })
    .append(
   开发者_运维问答     $('<img />').attr({
            'id'    : 'img',
            'src'   : 'edit.png'
    }))
    .appendTo('body');

Is the the "right way" to go about adding <a href="#"><img src="edit.png" id="img" /></a> to the body?

Also how would I add some css onto the img?


You can put all that directly into the jQuery() since version 1.4.x

$('<a />', {
    'href': '#'
})
.append(
    $('<img />', {
        'id'    : 'img',
        'src'   : 'edit.png',
        'css'   : {
            'width'  :  '100px',
            'height' :  '30px'
        }
}))
.appendTo('body');

This even works with events and data, you can say

$('<div/>', {
     id:    'myID',
     class: 'myCLASS',
     css:   {
         position: 'absolute'
     },
     click: function(e){
         alert(e.target.id);
     },
     data:  {
         foo:  'bar'
     }
}).appendTo(document.body);


$('<img/>').attr({
     'id'    : 'img',
     'src'   : 'edit.png'
 }).css({/* css here*/})

more on .css()


Not really recommended to do inline styles, but an example of CSS on an image is :

<img style="display:block;" src="##.jpg" />


TIMTOWTDI aside, yes, it is one way of doing it. Remember, there is no "right" right way. If it works, it means that you are on the right track.

Also, being right is relative.

0

精彩评论

暂无评论...
验证码 换一张
取 消