Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

jQuery CSS() for dynamically created elements

I'm using jQuery CSS function to style some elements

$element.css(style);

This works, but a part of the elements are created dynamically after the page load. This should be

$element.live ('created',function() {
$(this).css(style);
});

I'm stuck on the created event. Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There's no event for elements created (not universally available, anyway). You could

  • Add the rules to a stylesheet so that they are automatically applied to the newly created elements
  • Chain the css() method when you create your elements:

    $('<img id="createdImage" src="some.jpg"/>')
        .appendTo(document.body)
        .css(style);
    
  • Create a new stylesheet dynamically:

    $("<style>").text("#myNewEl { width:20px; height:30px; }").appendTo("head");
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...