Domanda

Given HTML such as

<div class="tpl grey">Hosts:
    <p>Hi !</p>
    <p>How are you ?</p>
    <p>What ever.</p>
    <a href="./~">An other child & element type !</a>
</div>

How to make that a click on a child element toggle the class="grey" of the closest parent .tpl element ?


The following code fails :

//Action to do on parent $(".tpl") 
var switch1 = function () {
    $(this).closest(".tpl").toggleClass("blue grey");
}

// On() click event
$(document).ready(function() {
        $(".tpl").on("click", "p", switch1() );
});

Fiddle: http://jsfiddle.net/MRcCy/1

È stato utile?

Soluzione

If you just want to toggle the closest .tpl (even though i only see one) try this

$(document).ready(function() { $(".tpl p").click(function(){ $(this).closest('.tpl').toggleClass('grey'); }); });

Altri suggerimenti

Check this fiddle

$(document).ready(function() {
    $(".tpl").click(function(){
        $('.tpl').toggleClass('grey blue');
    });
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top