jQuery只切换一个元素而不是全部

时间:2015-09-07 19:41:47

标签: javascript jquery jquery-ui

我有使用jQuery slidetoggle显示和隐藏特定列表的代码。我想点击一个加号/减号按钮来执行该事件。但每当我尝试使用viewWillAppeara.minuslinka > img时,除了ul之外,我无法使用任何选择器。有人可以帮忙吗?谢谢!

我的HTML:

.minusimg
		$("#xmlDiv").on("click", "ul", function(e) {
		  var clickedUl = $(this);
		  //alert(this);
		  clickedUl.children().find(".mainlist").slideToggle('slow', function() {
		    var img = clickedUl.find('span.minus img');
		    if (img.attr('src') === 'images/plus.png')
		      img.attr('src', "images/minus.png");
		    else
		      img.attr('src', "images/plus.png");
		  });
		});

MY JQUERY:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="xmlDiv">
  <ul class="section">
    <li class="root">
      <div class="minus">
        <a href="#" class="minuslink">
          <img src="images/minus.png" class="minusimg">  
        </a>
      </div>Antivirus Compliance - <a href="../xml/xml/1 - Sample AV.xml">Download</a>
      <ul class="mainlist" style="margin-left: -25px; display: block;">
        <li class="desc"> <span style="color:#e4e4e4;">-</span>  <span class="desc_span" tooltip="Antivirus is not installed.">AV Not Installed</span>
        </li>
        <li class="desc"> <span style="color:#e4e4e4;">-</span>  <span class="desc_span" tooltip="Antivirus is not running.">AV Not Running</span>
        </li>
        <li class="desc"> <span style="color:#e4e4e4;">-</span>  <span class="desc_span" tooltip="Antivirus is not updated.">AV Not Updated</span>
        </li>
        <li class="desc"> <span style="color:#e4e4e4;">-</span>  <span class="desc_span" tooltip="">Compliant</span>
        </li>
      </ul>
    </li>
  </ul>

1 个答案:

答案 0 :(得分:0)

如果我正确理解您的问题,问题很可能是从.mainlist链接的遍历。 这样做的一种方法是:$this.parent().siblings('.mainlist')

$("#xmlDiv div.minus").click( function(e) {
    var $this = $(this);
    $this.siblings('.mainlist').slideToggle('slow', function() {
        var img = $this.find('img');
        if (img.attr('src') === 'images/plus.png')
            img.attr('src', "images/minus.png");
        else
            img.attr('src', "images/plus.png");
    });
});

Fiddle

编辑:更改了点击以附加到&#39; .minus&#39; div,基本相同,但不需要parent()