使用 jQuery 获取兄弟元素的内容
我需要使用 jquery 获取某些特定元素的内容,问题是我的页面上重复有相同的元素:
<div class="content">
<img alt="" src="">
<p class="txt">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
<p class="info">Lorem ipsum dolor...</p>
<ul>
<li><a class="uiButton">Test</a></li>
</ul>
</div>
因此,div.content 在我的页面上重复多次,我只想获取 div 的内容保存按钮被点击。我在 .uiButton 上添加了一个 onclick 事件,并尝试使用父级(“.txt”)或兄弟姐妹(“.txt”),但似乎不起作用......
$(".uiButton").click(function(){
var txt = $(this).parent(".txt").text();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
.txt
不是父级,即使如此,它也必须是直接父级(.parent()
匹配直接父级如果它与选择器匹配),而不是您需要:替代方法是全部直到
.content
(通过.closest()
)为了安全起见,然后使用.find()
:.txt
isn't a parent, and even then it has to be a direct parent (.parent()
matches the immediate parent if it matches the selector), instead you need:The alternative is to go all the way up to
.content
(via.closest()
) to be safe then traverse down with.find()
:你需要向上到包装纸然后向下,你可以到兄弟姐妹那里,但在这种情况下会更难。
You need to go up to the wrapper and down, you can go to siblings, but in this case it will be harder.
可能有用。
Might work.