我正在构建一个 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/