سؤال

First of all: I am just starting to work with JS/Jquery. So please excuse any potential rookie mistakes. Now to the issue.

I have an item(a) with an hidden item(hidden_a). When i hover over item(a) item(hidden_a) shows up. So far so easy. But now i have several of this items on the page (for example: 10). Now is the question: How can i change my jquery snippet to success without writing the same snippets 10 times for 10 different selectors. Or is this even possible?

Thank you

Here the code:

 <ul >
            <li class="trigger"><a href="" >Item 1</a></li>
            <li class="trigger"><a href=""  >Item 2</a></li>

        </ul>

        <ul>
            <li style="display:none" class="target">
                <p >Hidden Item to Item 1</p>
            </li>
            <li  style="display:none" class="target">
                <p>Hidden Item to Item 2</p>
            </li>
        </ul>

<script>

$(".target").hide();
$(".trigger").hover(function(){
   $(".target").show();
},function(){
   $(".target").hide();
});

</script>
هل كانت مفيدة؟

المحلول

try to add for the outer element (a in your case) a class called outer, and for the inner elements add inner.

$(".outer").hover(function()
{
    //alert( $(this).find(".inner").show());
    $(this).find(".inner").show()
});

$(".outer").mouseleave(function()
{
    $(this).find(".inner").hide();
});

Make sure that the initial state of the .inner element is display: none.

Here is the example: http://jsfiddle.net/82weU/2/

نصائح أخرى

You could use a wrapper around each trigger and its corresponding target. Then you can look inside this wrapper for the corresponding target.

If you can't change the html structure, you can work with .index() https://api.jquery.com/index/ and .eq() https://api.jquery.com/eq/: Find the index of the hovered trigger and with its help the corresponding target.

Example code:

var $triggers = $(".trigger");
var $targets = $(".target").hide();

$triggers.hover(function(){
    var $currentTrigger = $(this);
    var indexOfTrigger = $triggers.index();
    var $correspondingTarget = $targets.eq(indexOfTrigger);
    $correspondingTarget.show();
},function(){
    var $currentTrigger = $(this);
    var indexOfTrigger = $triggers.index();
    var $correspondingTarget = $targets.eq(indexOfTrigger);
    $correspondingTarget.hide();
});

I'm late to the party, but heres another solution using index() and nth-child() that I think falls closer to what you might be looking for. Also the fiddle http://jsfiddle.net/S4aa9/

$(".hidden li").hide();
$(".trigger li").mouseenter(function(){
    //gets the nth position of the li
    var pos = $(this).index()+1;    
    $('.hidden li:nth-child('+pos+')').show();  
});

$('.trigger li').mouseleave(function(){
    var pos = $(this).index()+1;    
    $('.hidden li:nth-child('+pos+')').hide();
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top