簡體   English   中英

jQuery將CSS應用於動態創建的表行

[英]Jquery Applying CSS to Dynamically created table rows

我有一個HTML表,使用Jquery動態生成行。 行創建良好,並且動態生成的ID完美運行。 我想調整每次生成的表格單元的寬度。

<table border='1' id='foresttable'>
                        <tr>
                            <td id='addforestcell'><img id='addforestimg' src='img/addsign.png' onclick="forestrotate()"></td>
                            <td></td>
                        </tr>
                        <tr>
                            <td>Forest Area #1</td>
                            <td><img src='img/cancel.png' href="#" title='Start Over' onclick="clearForest();" class='deletebtn'> Place a Forest/Group of Trees on the Map</td>
                        </tr>
                    </table>

這是JQuery:

 $(function(){
var tbl = $("#foresttable");

$("#addforestimg").click(function(){
    $("<tr><td>Forest Area #"+forestnum+"</td><td class='forestcol2'><button class='red mapbtn' onclick='changecolor(this);' id='forestbutton"+forestnum+"'> Place markers to define forested area #"+forestnum+"</button></td><td>Lorem Ipsum</td><td>Lorem Ipsum</td><td><button class='delRowBtn'>Delete</button></td></tr>").appendTo(tbl); 
    if(forestnum>1){
        $("#foresttable tr:nth-last-child(2)").html("<tr><td>Forest Area #"+(forestnum-1)+"</td><td class='forestcol2'><button class='red mapbtn' onclick='changecolor(this);' id='forestbutton"+(forestnum-1)+"'> Place markers to define forested area #"+(forestnum-1)+"</button></td><td>Lorem Ipsum</td><td>Lorem Ipsum</td><td><button class='delRowBtn'>Delete</button></td></tr>");
    }
    $(".forestcol2").css("width", 800);
forestnum++;
});      
$(document.body).delegate(".delRowBtn", "click", function(){
    $(this).closest("tr").remove(); 

});    

});

創建的每一行都帶有刪除按鈕,但是我只希望最后一行是可刪除的,因此在創建新行時,我更改了倒數第二行的html以刪除它的刪除按鈕。

一切正常,但是創建后我不能更改倒數第二行的寬度。 好吧,我可以,但是只能通過在CSS中使用一系列ID選擇器來實現,例如

#forestbutton1{}
#forestbutton2{}
etc...

我已經嘗試將一個類應用於所創建的每一行(.forestcol2),如您在上面看到的那樣,它在創建它們時起作用,但是當我更改倒數第二個元素時不起作用嗎? 我也嘗試過:

$(".forestcol2").css("width", 800);

但沒有運氣。

困在這里任何幫助將不勝感激。

我注意到您在js中編寫了以下代碼。

tr:nth-last-child(2)

它選擇了表格的倒數第二個元素tr 這很有用吧? 您不需要知道這里的ID,而只需知道位置。

而且您知道,css還支持類似的功能。 根據您的要求,它應該像這樣。

#foresttable tr:nth-last-child(2){
 // any properties you want here
}

更多功能請訪問CSS3:nth-​​last-child()選擇器

很多小時后

不是css或JQuery,它們運行良好。 使用Chrome開發人員工具后,我可以看到它們已成功應用,但是有一些東西覆蓋了它們,並將寬度設置為68px,還有其他樣式。

我花了大約4個小時來仔細研究所有問題,以找出導致問題的原因,但是沒有運氣。

由於程序長數千行,因此不值得進一步研究,我將使用動態ID。

但是,感謝所有回答/評論的人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM