找不到此元素的正确 jQuery 选择器

Can't find the correct jQuery selector for this element

本文关键字:jQuery 选择器 元素 找不到      更新时间:2023-09-26

我有重复的html块,看起来像这样:

<div class="pod-control">
  <a class="fap-single-track"></a>
    <a class="pod-dl"></a>
    <div class="add-music"><a class="add_mycrate"></a></div>
    <div class="added-music"></div>
</div>

我正在使用jQuery从"a.add_mycrate"类中获取信息,然后对内容做一些ajax的东西,这一切都很好。

但是在响应中,我正在尝试.显示先前的.hiddendiv"添加音乐",但我似乎找不到正确的选择器。

这是我正在使用的:

var $this = jQuery(this);                  
    jQuery.post(myCrate.ajaxurl, data, function(response) {
        $this.closest('.add-music').remove();
        $this.closest('.pod-control').find('.added-music').show();
        alert(response);
    });

给我带来麻烦的台词是:

$this.closest('.pod-control').find('.added-music').show();

在阅读了一堆帖子后,我知道我需要将选择器移动到顶层(从 a.add_mycrate 到 .pod-control),这样我就可以 .find .add-music,但我也知道我做错了,因为无论我尝试什么都不会显示这个div。

在显示 .add-music ,尝试删除 .add-music。这意味着:交换警报上方的两行。

我的怀疑是,由于整个事件都绑定到被删除的链接,因此它也停止执行绑定到它的代码。

编辑:或者根本不删除()它,而是.hide()它。

问题是由 ul 元素中嵌套错误的标记引起的。 有关详细信息,请参阅此堆栈溢出答案。

一个可能的解决方案是做这样的事情:

<li class="pod-control">
  <a class="fap-single-track"></a>
  <a class="pod-dl"></a>
  <div class="add-music">
    <a class="add_mycrate"></a>
  </div>
  <div class="added-music"></div>
</li>

这样li里面的元素都共享一个公共的、可识别的父节点(.pod-control),使得它们更容易用JQuery .parent().children().siblings().next().prev()方法和:first-child:last-child:nth-child选择器等进行遍历和定位。