当 div 可见时,jQuery 将文本添加到 span

标签 jquery

<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/

相关文章:

javascript - HTML Select Text 上的 jQuery val() 优先于 Value

Javascript 使用鼠标单击并保持导航?

jQuery - 隐藏 el 并存储在数组中的属性

javascript - 如何绑定(bind)到所有点击事件,检查属性....有效?

javascript - 无需滚动即可修复 HTML 表格标题

jquery - MVC 动态部分 View 数据在 IE7 中消失

jquery - Materialise Navbar 下拉菜单/侧边栏下拉菜单不能一起工作

javascript - 将值字符串转换为 Javascript 数组的优雅方法?

jquery - Silverlight 和 "z-index"

jquery - jQuery如何实现通过类名获取元素?