簡體   English   中英

jQuery:附加到在另一個函數中創建的元素

[英]JQuery: Appending to an element created in another function

我這樣創建了一個div:

 $(document).ready(function() {
        $(document.createElement("div")).attr("id", "container").appendTo("body");
    });

然后稍后,我想動態地向其中添加一些內容,因此在另一個函數中,我調用了

$(newElement).appendTo("#container");

但它什么也沒做。 div仍然在那里,但是它是空的。 如果我將代碼更改為

$(newElement).appendTo("body");

它工作正常。 關於我在做什么錯的任何想法嗎?

這是我的代碼的完整示例:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $(document.createElement("div")).attr("id", "container").appendTo("body");
            });

            function add() {
                var newElement = $(document.createElement("div")).attr("id", "inner");
                $(newElement).appendTo("#container");
            }
        </script>
        <style type="text/css">
            #inner{
                background-color: black;
                height: 200px;
                width:100px;
            }
        </style>
    </head>
    <body>       
        <script language="JavaScript" type="TEXT/JAVASCRIPT">
            add();
        </script>
    </body>
</html>

您的add()函數在$(document).ready();之前被調用;

更改為此,它應該工作:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $(document.createElement("div")).attr("id", "container").appendTo("body");
                add();
            });

            function add() {
                var newElement = $(document.createElement("div")).attr("id", "inner");
                $(newElement).appendTo("#container");
            }
        </script>
        <style type="text/css">
            #inner{
                background-color: black;
                height: 200px;
                width:100px;
            }
        </style>
    </head>
    <body>       
    </body>
</html>

可以濃縮為:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
        <script type="text/javascript">
            $(function() {
                $("<div/>", { id : "container" }).appendTo("body");
                $("<div/>", { id : "inner"}).appendTo("#container");
            });
        </script>
        <style type="text/css">
            #inner{
                background-color: black;
                height: 200px;
                width:100px;
            }
        </style>
    </head>
    <body>       
    </body>
</html>

暫無
暫無

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

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