簡體   English   中英

javascript jQuery在頁面加載時打印到多個div?

[英]javascript JQuery printing to multiple divs on page load?

我基本上有幾個div,每個div的ID為“ id_1”,“ id_2”,“ id_3”等。這些div最初都是空的。

我想在頁面加載時以某些HTML內容填充所有div。 但是令我困擾的部分是,我還需要提取唯一的id部分以在html中使用:

<div id="id_3">
     <div id="inner_3></div>
</div>

內部div是要打印的內容。 請注意,“ 3”是通過javascript從容器div ID中提取的,然后在內部div中使用和打印。

任何想法如何做到這一點的jQuery? 提前致謝。

您可以獲取所有ID以特定字符串開頭div元素:

$(function() {
    $('div[id^=id_]').each(function() {
        var id = $(this).attr('id').split('_').pop();
        $(this).html(
            $('<div/>').attr('id','inner_' + id)
        );
    });
});

然后遍歷每個對象,獲取ID,然后進行HTML操作。

有幾種方法可以做到這一點,但最后只是簡單的字符串操作。 這是一個例子:

// on page load
$(function(){
    //find all divs and iterate through them - you can use any selector you like
    $("div").each(function(){
        //this gets the id attribute of the div we are currently on in the loop
        var id = $(this).attr("id");
        //this gets the number at the end - notice that its just string manipulation
        var nid = id.slice(id.lastIndexOf("_") + 1)
        //create inner div, give it an id and append
        var innerDiv = $('div').attr("id", "inner_" + nid);
        $(this).append(innerDiv);
        //all done - you can append content to inner div here
        // innerDiv.append(someContent);
    });
});

暫無
暫無

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

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