尝试使用nextSibling超文本标记语言获取下一个ID
<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”出了什么问题,有人吗?
发布于 2019-12-27 00:18:53
你的代码有几个问题:
1.选择器错误
$('id')将选择一个<id>元素。它并不存在。如果要将参数中的id用作选择器,则应按如下方式构造它:
$('#' + id)或者,您可以使用字符串插值:
$(`#${id}`)2. nextSibling()不是jQuery方法
您应该改用.next()。如果您确实需要使用本机Node.nextSibling属性,则需要首先访问底层DOM节点,即
$('#' + id)[0].nextSibling3.检查元素可见性的方式不正确
使用.css('display', 'none')将始终返回jQuery对象。它只是设置样式并返回用于链接的原始选择。如果要检查元素是否隐藏,则使用use .is(':hidden') instead。
其他评论
顺便说一句,你不应该使用内联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();
}
});https://stackoverflow.com/questions/59490780
复制相似问题