2016-05-17 165 views
2

我得到了元素列表,当我点击第一个其他10个也是活跃的, 如何只定位一个真正活跃的元素? 这是我的js代码jquery点击同一类的元素

$(document).ready(function() { 
    $('.inspiration-row').on('click', function() { 
     $('inspiration-block').toggleClass('shift-left shift-right'); 
     //$('.inspiration-block').toggleClass('span12 span8'); 
     $('.inspiration-right').toggleClass('span0 span2'); 
    }); 
}); 
+0

使用'$(this).toggleClass('shift-left shift-right');' – guradio

+0

是您的元素动态添加? – guradio

+0

不,它是静态列表 –

回答

1

我写了a fiddle来演示我的解决方案(让我知道它是否不完全符合你的意图)。

$(function($) { 
    $(document).on('click', '.inspiration-row', function(event) { 
    var target = $(event.target).closest('.inspiration-row'); 
    target.find('.inspiration-block').toggleClass('shift-left shift-right'); 
    //$('.inspiration-block').toggleClass('span12 span8'); 
    target.find('.inspiration-right').toggleClass('span0 span2'); 
    }); 
}); 

这将注册一个回调做好准备捕捉$因此,如果另一个脚本加载jQuery的,也不会影响到我们。它使用事件委托来捕获整个页面上发生的与.inspiration-row匹配的元素内的所有click事件。

event.target指的是事件的来源,事件来自的元素。我使用.closest从实际点击的那一个上搜索以找到匹配.inspiration-row的最近的祖先。

从那里,target指的是整个.inspiration-row,我们寻找这两个后代选择器并切换适当的类。

您正在切换两个类名,就好像这会让它选择一个或另一个。只有当元素最初具有这些名称之一时才是如此。我在第一个inspiration-row中添加了一个类名,这样在任何时候切换都会使它有一个或另一个。

+0

我扩展了小提琴测试用例来证明它解决了“页面上的每一个”问题。 – doug65536

+0

您的解决方案完美无缺,您是KING –

0

使用

$(this).toggleClass('shift-left shift-right'); 
+0

什么都没有,同样的问题 –

1

你可以像下面取代点击回调函数来定位你感兴趣的特定块:

function(event) { 
    $(event.target).closest('.inspiration-block').toggleClass('shift-left shift-right'); 
    ... 
}); 
0
Following is js fiddle link you can get answer for your question . modify according to your requirement . 

https://fiddle.jshell.net/sanjayarakeri/10xg1Lbq/ 

let us consider set of p tags in your html page . 

    <p class="active">If you click on me, I will disappear.</p> 
    <p>Click me away!</p> 
    <p>Click me too!</p> 
    <p>Click me one!</p> 
    <p>Click me two!</p> 
    <p>Click me three!</p> 
    <p>Click me four!</p> 

to handle active p tag use following jquery code. 

    $(document).ready(function() 
    { 
     $("p").click(function(event) 
     { 
      $(event.target.tagName).not(this).removeClass("active"); 
      $(this).addClass("active"); 
     }); 
    }); 

Add this class in your html page in style tag . 

    .active { 
    display: block; 
    color: red; 

}