javascript - 构建嵌套 jquery 对象并附加到内部元素

标签 javascript jquery

我正在构建一个 jquery 对象:

 function build(){
     var first = $('<div/>', {
        class: 'first'
    });
    var second = $('<div/>', {
        class: 'second'
    });
    var third = $('<div/>', {
        class: 'third'
    });
    second.append(third);
    return first.append(second);
}

现在我想在第三个对象返回后将新元素附加到它。尝试过obj.find('.third').append(...)但这不起作用。 有什么想法可以做到这一点吗?

谢谢。

最佳答案

不要使用find方法。您可以使用 children()

实现相同的效果

试试这个:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function getme(){
    var first = build();
    var fourth = $('<div/>', {
      class: 'fourth'
    });
    first.children().children().append(fourth)
    console.log(first);
}
function build(){
     var first = $('<div/>', {
        class: 'first'
    });
    var second = $('<div/>', {
        class: 'second'
    });
    var third = $('<div/>', {
        class: 'third'
    });
    second.append(third);
    return first.append(second);
}
</script>
</head>
<body>

<button onclick="getme()"/>

</body>
</html>

关于javascript - 构建嵌套 jquery 对象并附加到内部元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48439223/

相关文章:

javascript - 隐藏/显示 ngFor 内的单个或特定按钮

javascript - 如何使用 goog.provide 和 goog.require 加载我自己的 js 模块?

javascript - 无法从 div 启动 Stellar.js

javascript - jQuery DataTable 添加行第一位置

javascript - 如何始终显示在 HTML Select 中选择的第一个选项?

javascript - 使用 glob() 的 php/html5 播放列表

javascript - 将数据表行子级与通过 foreach 显示的列表一起使用

javascript - 当 xaxis 是文本时,如何显示 jqplot 堆积条形图?

ajax - 无法通过 jQuery Ajax 发送 POST 请求

javascript - 选择的选项有什么问题?