尝试使用 nextSibling 获取下一个 ID .HTML
<div class="flex relative" onclick="TradeThis(this.id)" id="1" style="cursor:pointer">
<div class="relative flex-1 mr-1">
<div class="px-3 text-xs text-center text-white border border-red-700">
<div class="text-xxs">
SELL • EUR
</div>
<div class="mb-4">
1.10<span class="text-3xl font-bold leading-none">28</span>3
</div>
</div>
<div class="absolute p-2 red-border-box right-0 bottom-0"></div>
</div>
</div>
.JS
function TradeThis(id) {
if ($('id').css("display", "none")) {
($('id').nextSibling).show().siblings('div').showAll();
} else if ($('id').nextSibling).css("display", "none")) {
$('id').show().siblings('div').showAll();
}
}
id 为"1" 下一个 ID 应为"2" 出了点问题,有人吗?
您的代码存在几个问题:
1. 选择器不正确
$('id')
将选择一个<id>
的元素。它不存在。如果要使用参数中的id
作为选择器,则应按如下方式构造它:
$('#' + id)
或者,您可以使用字符串内插:
$(`#${id}`)
2.nextSibling()
不是jQuery方法
您应该改用.next()
。如果你真的需要使用原生Node.nextSibling
属性,你需要先访问底层的 DOM 节点,即
$('#' + id)[0].nextSibling
3. 检查元素可见性的方法不正确
使用.css('display', 'none')
将始终返回 jQuery 对象。它只是设置样式并返回原始选择以进行链接。如果要检查元素是否隐藏,请改用.is(':hidden')
。
补充说明
附带说明一下,您不应该真正使用内联 JS 来绑定点击事件。您可以为元素提供一个类,您可以在其中绑定点击事件侦听器,例如:
<div class="flex relative trade-this" id="1" style="cursor:pointer">
然后在你的jQuery逻辑中,你可以这样做:
$('.trade-this').on('click', function () {
var $t = $(this);
if ($t.is(':hidden')) {
$(this).next().show().siblings('div').showAll();
} else if ($t.next().is(':hidden')) {
$t.show().siblings('div').showAll();
}
});