Question

I'm trying to invoke slideToggle on a div in the page based on the href of an anchor inside a list item. I've never used the :only-child selector before, is there a reason I can't use it with (this)?

$('li').click(function(){
    var requiredID = $(this:only-child).attr('href');
    $('#requiredID').slideToggle();
});

JSFiddle: http://jsfiddle.net/QW32X/2/

To clarify, the particular interface I'm working on is going to require that the li itself be clicked on, which is why I can't just get the id directly from the anchor itself.

Était-ce utile?

La solution

I think that there is no need to use it but if you want to seek for the a element that is the only child this will work

$('li').click(function(){
    var requiredID = $(this).children("a:only-child").attr("href")
    $(requiredID).slideToggle();
});

Working Fiddle

Autres conseils

You certainly can, but you can't append it to a variable. Try this:

var requiredID = $(this).filter(':only-child').attr('href');

Better:

$('li:only-child').click(function(){
    var requiredID = $(this).attr('href');
    $('#requiredID').slideToggle();
});

All that said, this won't work because you have no only-child list items in your fiddle. Furthermore, no list should be created with the intention of it only having one item. That's not much of a list.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top