【问题标题】:Find previous element with jQuery - not a sibling使用 jQuery 查找前一个元素 - 不是同级元素
【发布时间】:2014-10-22 22:39:12
【问题描述】:

我需要为一些元素附加 onclick 事件。这些点击事件需要对应以下元素。

例如:(jsfiddle here)

HTML:

<span class="s1">s</span>
<span class="s2">s</span>
<div class="divs"></div>
<br/>
<br/>
<span class="s1">s</span>
<span class="s2">s</span>
<div class="divs"></div>
<br/>
<br/>
<span class="s1">s</span>
<span class="s2">s</span>
<div class="divs"></div>

CSS:

.divs{
    background:lightblue;
    width:50px;
    height:50px;
    margin:10px;
}

span{
    background:pink;
    margin:10px;
    padding:10px;
}

JQUERY:

$(function(){
    divs = $('.divs');

    divs.each(function(){
        $this = $(this);

        s1 = $this.closest('span').find('.s1');
        s2 = $this.closest('span').find('.s2');

        s1.click(function(){
            alert('S1 click');
            $this.css('background', 'green');
        });

        s2.click(function(){
            alert('S2 click');
            $this.css('background', 'blue');
        });
    });
});

我想点击任意一个 span 元素并对下面的 div 执行操作。

【问题讨论】:

  • .next 接受选择器作为参数。您需要使用$this.next('div.divs')
  • @SergiuParaschiv 只过滤下一个跟随元素,需要使用.nextAll('.divs:first')
  • 对了,忘记了。
  • 你能用 jsfiddle 演示吗?我不太明白这将如何工作,谢谢:)

标签: jquery html css jquery-selectors onclick


【解决方案1】:

试试这个:

<div class="wrapper">
<span class="s1">s</span>
<span class="s2">s</span>
<div class="divs"></div>
</div>
<br/>
<br/>
<div class="wrapper">
<span class="s1">s</span>
<span class="s2">s</span>
<div class="divs"></div>
</div>
<br/>
<br/>
<div class="wrapper">
<span class="s1">s</span>
<span class="s2">s</span>
<div class="divs"></div>
</div>

还有 jQuery 部分:

$(function(){

    $('span.s1').on('click',  function () {
        $(this).parent().find('.divs').css('background', 'green');
    });

    $('span.s2').on('click', function () {
        $(this).parent().find('.divs').css('background', 'blue');
    });

});

【讨论】:

    【解决方案2】:

    我认为您不需要将事件侦听器包装在每个函数中。 我很确定这会起作用(并减少代码量):

    $(function(){
      $('.s1').click(function() {
        alert('s1 clicked');
        // If you want to change all of the .divs
        $(this).siblings('.divs').css('background', 'green');
        // If you just want to change the first .divs
        $(this).next().next().css('background', 'green');
      });
    
      $('.s2').click(function() {
        alert('s2 clicked');
        // If you want to change all of the .divs
        $(this).siblings('.divs').css('background', 'blue');
        // If you just want to change the first .divs
        $(this).next().next().css('background', 'blue');
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2015-06-02
      • 1970-01-01
      • 2011-10-24
      • 2018-02-12
      • 1970-01-01
      • 1970-01-01
      • 2011-07-09
      • 2010-12-20
      • 2012-03-07
      相关资源
      最近更新 更多