CSS没有'使用javascript向页面动态添加元素时无法工作

CSS doesn't work when dynamically adding elements to page using javascript

本文关键字:元素 添加 动态 工作 没有 使用 javascript CSS      更新时间:2023-09-26

我想动态地向页面添加新闻更新。当你登录时,你会得到20条新闻。向下滚动到底部,有一个"更多"按钮。单击它,一些ajax会从服务器上以json形式再获取20个。Javascript将json解析为名称、日期、注释、图片等。

好消息是它有点奏效。我可以为每个名称、日期注释等创建文本节点,并将它们添加到id="more"div中,这一切都会在简介中出现。

如何将其转换为与周围div相同的格式?我会尽可能简短地说。。。

三列布局,内部三列布局。。。

<div class="wrapper threecol">
<div class="colmid">
    <div class="colleft">
        <div class="col1">
            <div class="friends">   
            <div class="colwrap st-leftmenu">
                <c:forEach var="st" items="${news}">
                <div class="st-colleft">
                <div class="st-col1">
                <div class="statusName">
                    ${st.name}
                </div>
                        <%-- date, comment, pic etc. omitted --%>
                </div> <%-- end st-col2 --%>
                </div> <%-- end div class st-colleft --%> 
                </c:forEach>
                </div> <%-- end div class colwrap st leftmenu --%>
                        <%-- add new stuff here dynamically --%>
                <div id="showExtra"></div>
                <a href="javascript:void(0)" onclick="moreStatus()">get more</a>
            </div> <%-- end div class friends --%>
            </div> <%-- end col1 --%>

我正在尝试添加到id="showExtra"div中,它的部分工作原理如上所述。我尝试在js中创建一个复杂的嵌套div结构。这让我走了一段路,但这不可能是实现目标的方式。。。有点乱,对不起。。。

function showMoreStatus(){
var moreDiv = document.getElementById('showExtra'); 
var moreJSON = new Array();
if(request.readyState == 4) {
    if (request.status == 200) {
        moreJSON = eval('(' + request.responseText + ')');
        for(var i=0; i<moreJSON.length; i++) {              
            //get values from JSON
            var JSONName = moreJSON[i][2];
                            // and others...
            //create text nodes, a href and img
            var nameTextNode = document.createTextNode(JSONName);
                            // and other nodes, imgs, hrefs etc...
                            // surely this is NOT the way to do it!             
            //column divs
            var outColDiv = document.createElement("div");
            outColDiv.setAttribute("class", "col1");
            var friendsDiv = document.createElement("div");
            friendsDiv.setAttribute("class", "friends");
            var colLeftDiv = document.createElement("div");
            colLeftDiv.setAttribute("class", "st-colleft");
            var col1Div = document.createElement("div");
            col1Div.setAttribute("class", "st-col1");
            var col2Div = document.createElement("div");
            col2Div.setAttribute("class", "st-col2");
            colLeftDiv.appendChild(col1Div);
            colLeftDiv.appendChild(col2Div);
            friendsDiv.appendChild(colLeftDiv);
            outColDiv.appendChild(friendsDiv);

            var nameDiv = document.createElement("div");
            nameDiv.setAttribute("class", "statusName");
                            // and others...
            // append nodes to divs
            nameDiv.appendChild(nameTextNode);
            col1Div.appendChild(nameDiv);
            col1Div.appendChild(dateDiv);
            col1Div.appendChild(contentDiv);
            // append the page
            moreDiv.appendChild(outColDiv);
        }
    }
}

}

啊!谢谢你读到这里。

嗯,那真的一点也不简短。事实上,这可能没有必要。

这里的正确方法是什么?如何让nameTextNode和他的所有朋友与${st.name}坐在同一个地方?

您没有显示您的CSS,所以很难说到底是什么在破坏。我的猜测是,因为您在这个"showExtra"div中嵌套了新元素,所以您破坏了CSS选择器。您可能只需要在与现有元素相同的级别添加新元素,即在这个元素中

<div class="colwrap st-leftmenu">

此外,您可能还需要查看标签中id属性的使用情况。Id应该是唯一的值,并且基于您的循环结构,看起来您会得到多个具有相同Id"statusNameDiv"的项目。

一般概念是,如果HTML元素与给定的CSS选择器匹配,则CSS应该适当地应用于HTML元素。即使您通过AJAX动态添加它们。

我建议你确保CSS是防弹的。我想这可能是你的第一个痛点。如果你有一个新闻项目列表,设置一个HTML列表,比如:

<ul id="news">
    <li><!-- News Block 1 --></li>
    <li><!-- News Block 2 --></li>
    <li><!--     ...      --></li>
    <li><!-- News Block N --></li>
</ul>

在每个新闻"块"中,您可以根据需要构建一些HTML。例如:

<li>
    <h2>News title 1</h2>
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
    <p>Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
    <a href="#" class="read-more">Read More about News 1</a>
</li>

然后,您可以为所有区块设置"新闻区块"的样式。

#news h2{
    font-weight:600;
    font-family:Arial, Sans-Serif;
}
#news .read-more{
    text-decoration:none;
    color:#FF00FF;
}

从那里,你所需要做的就是用JavaScript/AAJAX获取和格式化你的数据,并附加LI"块"。使用jQuery可以帮助实现这一点。

以下是一些粗略的pseduo代码:

// get news items from AJAX
var newsList = $.ajax().getNews(10);
// loop through all new news items
for(i=0;i<newsList.size;i++) {
    // get a formatted LI block
    var block = formatNewsBlock(newsList[i]);
    // append news block to end of news list
    $('#news').append(block);
}

一个好的结构可以帮助事情更容易实现。

我希望这能帮助到一些人!

干杯!