【问题标题】:$this.parent().find .removeClass doesnot remove class$this.parent().find .removeClass 不删除类
【发布时间】:2015-01-18 15:08:34
【问题描述】:

我有以下问题

如果我在循环中添加一个额外的列,则不会通过 jquery 脚本删除 ccs 类。如果我删除它就可以了..

<?php foreach ($option['option_value'] as $option_value) { ?>
    <td>
       <a class="option-detail"> <img src="image"></a>
    </td>
<?php } ?>   

我做错了什么?

部分jquery代码

$(document).ready(function(){
      $("a.option, a.option-detail").click(function(event){
         $this = $(this);
         $this.parent().find('a.option, a.option-detail').removeClass('option-active');
        $this.addClass('option-active');

【问题讨论】:

    标签: php jquery jquery-selectors


    【解决方案1】:

    这是因为parent 不足以让您到达您需要更改的节点所在的顶层。

    I.E.你只是向上移动到包含tdtr,而不是table

    如果没有更多代码(更多的 HTML 生成),就很难确定。

    我的最佳猜测是您实际上需要找到closest 表而不是parent

    例如

    $this.closest( 'table' ).find('a.option, a.option-detail').removeClass( 'option-active' );
    

    This fiddle give you an example of what I'm suggesting...

    【讨论】:

      【解决方案2】:

      使用&lt;a class="option-detail"&gt;&lt;img src="image"&gt;&lt;/a&gt;(之前去掉a.

      因为这样:

      &lt;a class="a.option-detail" &lt;img src="image"&gt;&lt;/a&gt; 你的班级名称将是.a.option-detail

      并通过关闭 &gt; 来修复您的 htm

      【讨论】:

      【解决方案3】:

      您为什么要在“a.option”上进行点击事件,然后在删除和添加类之前再到父级并再次找到锚点?这样做会不会更容易:

      $(document).on('click', 'a.option, a.option-detail', function() {
          $this = $(this);
          $('.option-active').removeClass('option-active');
          $this.addClass('option-active');
      }
      

      【讨论】:

      • 更正了 html .. 是写问题时的一种类型 :(
      • @cappy39 别担心,更新了答案,希望对你有用。
      • 谢谢您的响应,我将在循环中具有图像,并且在选择其他图像时,应从活动的其他图像中删除CSS样式,并将其设置为我所拥有的单击.. 当我再次单击它时,使用 toggleClass 删除样式,这不是我想要的
      • 难道你不能只找到具有“option-active”的那个 - 将其删除然后将其设置为当前那个而不是通过父项找到吗?
      • 这行得通,假设屏幕上只有一个表可以有活动选项。如果有两个,那么单击一个将清除两个表上的活动选项类。
      猜你喜欢
      • 2019-04-16
      • 2013-04-27
      • 2013-09-29
      • 1970-01-01
      • 1970-01-01
      • 2013-01-10
      • 2020-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多