开发者

Help Targeting element

I have the following code:

$(".main").click(function() {
    $(this).toggleClass("classA").toggleClass("classB");
    $(".secondary").toggleClass("classC").toggleClass("classD");
));

$(".secondary").click(function() {
    $(".secondary").toggleC开发者_运维知识库lass("classC").toggleClass("classD");
));

And HTML:

<div class="main"></div>

<div>
    <div class="secondary"></div>
    <table class="tbl"></table>
</div>

<div>
    <div class="secondary"></div>
    <table class="tbl"></table>
</div>

Currently it allows me to toggle class when each "secondary" element is clicked individually or change for all secondary when "main" is clicked. I need to add show/hide table in appropriate div when corresponding "secondary" or "main" is clicked. Having difficulty targetting. Tried but failed:

$(this).closest(".tbl").toggle();


try this:

$(".secondary").click(function() {
    $(".secondary").toggleClass("classC").toggleClass("classD");
    $(this).parent().children(".tbl").toggle();
 //or this: $(this).next(".tbl").toggle();
));


I'm not sure I'm exactly understanding what you're asking, but have a look at this demo: http://jsfiddle.net/Ender/DQcSE/

Here's the source for that:

$(".main").click(function() {
    $(this).toggleClass("classA classB");
    $(".secondary").each(toggleSecondary);
});

$(".secondary").click(toggleSecondary);

function toggleSecondary() {
    $(this).toggleClass("classC classD")
           .next('.tbl').toggle();
}

I've set up a function to generically handle toggling for a .secondary. In the .main click handler, the main classes are toggled, and the secondaryToggle() function is invoked on each .secondary. In the .secondary click handler, secondaryToggle() is invoked only on the clicked element.

secondaryToggle() toggles the classes of that element, and selects the next element (only if it has class .tbl) and toggles its visibility.

Note also that you need not call .toggleClass() for each class - you can pass it a space-separated list of classes toggle, much like you can do with .addClass() and .removeClass().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜