我有一个包含 3 个 DIV 元素的 DIV block :赞成票、投票和反对票。当我单击赞成票或反对票并在 JQuery 代码块中调用 parent.html(html) 时,它会将投票计数覆盖在赞成票或反对票图标上。我将使用哪个 JQuery 调用来访问 DIV 类“投票”?我会找到父元素的父元素然后搜索“votes”类吗?有什么方法可以按名称查找元素的 sibling 吗?抱歉这个新手问题,但我对 JQuery 还是很陌生!
最佳答案
假设您的加价大约是:
<div>
<div class="upvote">vote up</div>
<div class="votes">0</div>
<div class="downvote">vote down</div>
</div>
您可以使用:
$('.upvote').siblings('.votes');
或者:
$('.upvote').parent().find('.votes');
引用资料:
- >
siblings()
: JS Fiddle , - >
parent()
, - >
find()
.
编辑以回应 OP 的问题(在评论中):
Ohhhh no it's not a problem with there being more than one sibling '.votes' div. The problem is that there are more than one submissions on a given page and when you upvote one the rest get upvoted as well. I think this is why I need to use $this or something to only use the selected submission. Any ideas?
我不确定您所说的“给定页面上有多个提交”到底是什么意思,但我假设您的意思很简单,即页面上有多个投票元素。如果是这种情况(并且我假设加价与我在本答案的第一部分中估计的一致),您可以使用:
$('.upvote').click(
function(){
$(this).siblings('.votes');
// this is just a selector, it won't 'do' anything
// other than select the element.
});
关于javascript - 如何使用 JQuery 设置同级元素的 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5175571/