尝试使用Javascript动态更改CSS失败.为什么?



我用一个基于PHP的服务器端程序制作了一个简单的公告板系统,该程序可以生成JSON响应。

对于客户端,我选择使用jQuery动态生成所有HTML代码。

<body>
<ol class="list" id="viewList"></ol>
$(document).ready(function () {
  $.getJSON("list.php", function (json) {
    var nPosts = json.length;
    for (i = 0; i < nPosts; i++) {
        $('<ol/>', {
            class: "viewPost",
            id: "post" + i
        }).appendTo("#viewList");
        $('<li/>', {
            class: "viewAuthor",
            id: "author" + i,
            text: json[i].authorName
        }).appendTo("#post" + i);
        $('<li/>', {
            class: "viewEmail",
            id: "email" + i,
            text: json[i].authorEmail
        }).appendTo("#post" + i);
    }
  });
  //Problem HERE:    
  var post0 = document.getElementById("post0");
  post0['style']['border-top-width'] = '0px';
});

我在这里所做的是,删除虚线,只用于第一个列表项(li)。

尝试了两种jQuery方式($("#post0")…)和Javascript方式(如上)但两者都没有生效。

.list {
    border-style: solid; border-width: 1px;
    width: auto;
    padding: 0px;
}
.viewPost {
    border-style: none;
    border-top-style: dashed; border-top-width: 1px;
    padding: 0px;
}

问题是,当加载文档时,不会生成这些元素,因此jquery没有任何记录表明这些元素存在。

所以要解决这个问题,你必须在jquery中使用委托方法,比如

$(document).on('click',"class_or_id_which_is_created_runtime", function(e){
    //your code here 
    }); 

或者您可以在创建这些元素时添加javascript函数

$('<ol/>', {
        class: "viewPost",
        id: "post" + i onClick=blah();
    }).appendTo("#viewList");

与其用这种方式(使用javascript),不如看看CSS伪类:first-child:

ol li {
/*CSS properties for all elements here*/
}
ol li:first-child {
/* Specific CSS properties for the first element here */
}

注意:另请参阅可能对您有用的:last-childnth-child()注意2:请注意,只有IE9…才支持此功能

在内存中创建集合,只需检查索引是否为0,在循环中添加适当的样式,并在构建后附加所有内容:

$(document).ready(function () {
    $.getJSON("list.php", function (json) {
        var elems = $([]);
        $.each(json, function (index, value) { // assuming it's an array
            var ol = $('<ol />', {
                'class' : 'viewPost',
                id      : 'post' + index
            }),
            li1 = $('<li />', {
                'class' : 'viewAuthor',
                id      : 'author' + index,
                text    : value.authorName
            }),
            li2 = $('<li />', {
                'class' : 'viewEmail',
                id      : 'email' + index,
                text    : value.authorEmail
            });
            if (index === 0) ol.css('border-top-width', '0px');
            elems = elems.add(ol.append(li1, li2))
        });
        elems.appendTo('#viewList');
    });
});

相关内容

最新更新