문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top