<div class="box">
<span class="test"></span>
</div>
<div class="row"></div>
<input type="button" value="Add" id="button">
<style type="text/css">
.box {
display: none;
}
</style>
页面加载时,上面的 div 不可见。我们正在使 div 在按钮单击后可见。现在我想在 div 可见时将文本附加到 span。
$('#button').on("click",function(e){
e.preventDefault();
$('.box').clone().show().append('.row');
});
我试过了
1) $(".box").closest(".test").text("hello");
2) $(".box").find(".test").text("hello");
但它没有将文本添加到跨度中。
最佳答案
.closest
遍历父元素。您需要使用 .find()
而不是 .closest()
选择器来搜索子元素:
$(".box .test").text("hello");
或
$(".box").find(".test").text("hello");
<强> Working Demo
关于当 div 可见时,jQuery 将文本添加到 span,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39464106/