使用 jQuery 获取兄弟元素的内容

发布于 2024-10-08 20:02:51 字数 625 浏览 13 评论 0 原文

我需要使用 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(); 
}

I need to get the content of some specific elements using jquery, the problem is that i have the same element repeating on my page:

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

So, the div.content repeat on my page many times and I want to get only the contents of the div that holds the button was clicked. I've added a onclick event on the .uiButton and tried to use parent(".txt") or siblings(".txt"), but dont seems to work...

$(".uiButton").click(function(){ 
  var txt = $(this).parent(".txt").text(); 
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夜无邪 2024-10-15 20:02:51

.txt 不是父级,即使如此,它也必须是直接父级(.parent() 匹配直接父级如果它与选择器匹配),而不是您需要:

$(".uiButton").click(function(){ 
  var txt = $(this).closest("ul").siblings(".txt").text(); 
});

替代方法是全部直到 .content (通过 .closest() )为了安全起见,然后使用 .find()

$(".uiButton").click(function(){ 
  var txt = $(this).closest(".content").find(".txt").text(); 
});

.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:

$(".uiButton").click(function(){ 
  var txt = $(this).closest("ul").siblings(".txt").text(); 
});

The alternative is to go all the way up to .content (via .closest()) to be safe then traverse down with .find():

$(".uiButton").click(function(){ 
  var txt = $(this).closest(".content").find(".txt").text(); 
});
娇俏 2024-10-15 20:02:51

你需要向上到包装纸然后向下,你可以到兄弟姐妹那里,但在这种情况下会更难。

$(".uiButton").click(function(){ 
  var txt = $(this).closest('.content').find('.txt').text(); 
}

You need to go up to the wrapper and down, you can go to siblings, but in this case it will be harder.

$(".uiButton").click(function(){ 
  var txt = $(this).closest('.content').find('.txt').text(); 
}
风月客 2024-10-15 20:02:51
$(this).closest('p.txt');

可能有用。

$(this).closest('p.txt');

Might work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文