0

I like it that data gets called through jQuery ajax. Clean coding and it looks slick.

I'm wondering if the code below is the correct way to do this. It works (that's one thing), but i'm not sure if applying the css that way is the correct way :s.

I know some questions here apply to the same, but those questions are more specific to one problem. I want to know what is the best practice.

Thanks in advance!

$.ajax('db/getLatestAlbums.php').done(function(data) {
    //populate albums ul
    var items = [];
    obj = $.parseJSON(data.trim());
    $.each(obj, function(id, value) {
        items.push('<li data-category="' + value.category_name + '"><a href="#"><img alt="' + value.album_name + '" src="' + value.album_cover + '"></a><p><a href="#">' + value.album_name + '</a><span>' + value.category_name + '</span></li>');
    });
    $("ul#albums_list").html(items.join(''));
    $("ul#albums_list li").css({
        "background": "none repeat scroll 0 0 #252525",
        "border-radius": "3px 3px 3px 3px",
        "float": "left",
        "height": "300px",
        "margin": "10px 11px 10px 10px",
        "padding": "0",
        "width": "225px",
        "display": "inline-table"
    });
    $("ul#albums_list li a").css({
        "overflow": "hidden",
        "display": "block",
        "position": "relative"
    });
    $("ul#albums_list li a img").css({
        "display": "block",
        "position": "relative",
        "border-radius": "3px 3px 3px 3px",
        "height": "221px",
        "width": "221px",
        "margin": "2px",
        "border": "medium none"
    });
    $("ul#albums_list li p").css({
        "margin-top": "20px",
        "padding": "0 10px",
        "text-align": "center"
    })
});
4

3 回答 3

4

任何 CSS 都将应用于页面上的元素,即使它们是通过 ajax 加载的。只需将其移至您的 CSS 文件即可。

于 2013-05-25T15:37:32.560 回答
2

取决于您要达到的目标。如果您只是简单地尝试将样式应用于新加载的内容,那么就像其他评论所说,只需将其放入您的 css 规则中,它将在加载时自动应用。

但是,如果您想为其添加逻辑,即根据加载的内容不同的 css,这将是一种方法,但最好在 css 中定义不同的类并简单地使用 addClass() 和删除类()。

于 2013-05-25T15:50:22.577 回答
2

只需将其移动到 css 文件,具有特定类名的 ajax 内容将与定义的属性一起应用。

于 2013-05-25T15:42:34.437 回答