jQuery CSS() for dynamically created elements

强颜欢笑 提交于 2019-11-27 02:12:12

问题


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?


回答1:


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");
    



回答2:


Best Idea is to Define CSS classes. And then Remove and add classes from Dynamic elements as per need

$(element).addClass("className");
$(element).removeClass("className");

Example: JS Fiddle




回答3:


$('head').append('
< style >
.folder { background: url(../icons/Folder_icons/g/f.png) no-repeat left top;} < / style >');


来源:https://stackoverflow.com/questions/3717257/jquery-css-for-dynamically-created-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!