JQuery .is con múltiples selectores

I have a div with a number of nested span elements within it. The intention is that the div has its class updated whenever a user clicks it or any element contained within it. It must act before and after an AJAX call. The code I have is:

$(document).ready(function() {
    calcPackCosts();
    $("#CentredContainer").click(function(event) {
        if($(event.target).is(".smBut")) {
        // NOTE: utilises event bubbling to ensure ajax items are seen when they are returned to the page
        // get the type of button 
        var $mode = $(event.target).get(0).name;
        //extract the index from the id
        var $index = $(event.target).get(0).id;
        var $itemindex = $index.match(/\d+/)[0];    
        var $numPacks = $("div[id*='giftoption_1_'].selectedpack").length;
        var $numItems = $(".giftPacks").length;

        submitForm('ExperienceCart',$mode,$itemindex,$numPacks);
        }

        if($(event.target).is(".package")) {        // a gift package option has been selected

            //extract the index from the id
            var $itemindex = $(event.target).get(0).id;
            var $packSelected = $itemindex.match(/\d+/)[0]; // get the first number in the string id
            var $rowIndex = $itemindex.match(/(\d+)$/)[0];  //get the last number in the string id
            unselectAll($rowIndex);
            $(event.target).addClass("selectedpack");

            // update the deliverymethod in the cart with the selected packselected  and
            // calculate and update the packaging costs
            calcPackCosts($rowIndex,$packSelected);
        }
    });
});

<div id="CentredContainer" >
    <H1 class="ProductTitle">My Basket</H1>     
    <div class="PagesBar" style="width:96%;">

<div>
                <p>Select your gift packaging:</p>
              </div> 

              <div class="giftPacks">
                <div class="left mr-10 giftpack">
                    <div class="Tile120 margT10 package" id="giftoption_1_<%=itemCounter%>" >

                            <span class="left mr-5 giftIcon1"></span>

                        <span class="giftIconText">Gift Pack</span><br />
                        <a href="#" title="Gift Pack" class="thickbox left mr-5"><span class="questionIcon"></span></a>
                        <span class="left mr-5" style="line-height:5px;">$5</span>
                    </div>
                </div>



                <div class="left mr-10 giftpack">
                    <div class="Tile120 margT10 package" id="giftoption_2_<%=itemCounter%>" >

                            <span class="left mr-5 giftIcon2"></span>

                        <span class="giftIconText">Envelope</span><br />
                        <a href="#" title="Gift Pack" class="thickbox left mr-5"><span class="questionIcon"></span></a>
                        <span class="left mr-5" style="line-height:5px;">Free</span>
                    </div>
                </div>


                <div class="left mr-10 giftpack">
                    <div class="Tile120 margT10 package" id="giftoption_3_<%=itemCounter%>">

                            <span class="left mr-5 giftIcon3"></span>

                        <span class="giftIconText">Email</span><br />
                        <a href="#" title="Gift Pack" class="thickbox left mr-5"><span class="questionIcon"></span></a>
                        <span class="left mr-5" style="line-height:5px;">Free</span>
                    </div>
                </div>


                <span class="right paddT20" style="display:inline;">

                    <input type="button" class="submitBut smBut" name="Add" id="Add<%=itemCounter%>" value="Add Another">
                    <input type="button" class="submitBut smBut" name="Remove" id="Remove<%=ExperienceCart.DisplayIndex%>" value="Remove">
                </span>


            </div>
           </div>

Note that <%=itemCounter%> is simply a count of the row. Rows are added through the Add button via an AJAX call.

The area I have a problem with is if($(event.target).is(".package")) { and $(event.target).addClass("selectedpack");

where it is supposed to handle any element in the div containing .package - it only handles the div however and does not respond to the spans.

He intentado :

  • if($(event.target).is(".package, .package span"))

  • if($(event.target).is(".package, span"))

  • if($(event.target).is(".package","span"))

But all these work on is the div .package. It ignores the spans within the div.

preguntado el 01 de febrero de 12 a las 22:02

No veo el #CentredContainer en su código. -

Can you copy the right markup? -

<div id="CentredContainer" > wraps the entire html code -

2 Respuestas

click events bubble up the DOM. So if you click on a nested element, that event will bubble up to the ancestor elements of the initial target. So to capture all the click events in a container (including the ones targeted on it's children) all you have to do is set a click event handler on the container element:

//wait for `document.ready` to fire
$(function() {

    //find all element with the `.package` class and bind a click event handler to them
    $(".package").click(function() {

        //the element has received a click, `.toggleClass()` will do just what it states, if the class is present it will be removed, and if it isn't present it will be added
        $(this).toggleClass('some-class');

Aquí hay una demostración: http://jsfiddle.net/KC3yC/2/

Also, if you are just checking to see if an element has a class, you can use .hasClass() en lugar de .is(): http://api.jquery.com/hasclass

Noticias

If your elements are added dynamically to the DOM then you can delegate the click controlador de eventos:

$(function() {
    $("#CentredContainer").delegate(".package", "click", function() {
        $(this).toggleClass('some-class');
    });
});

Respondido el 20 de junio de 20 a las 12:06

Many thanks Jasper. The elements can be added dynamically through AJAX calls. I tried hasClass being the easiest to test but this didn't work. - Phil Williams

I also tried adding in the function under your Update but couldn't get this to work either. It worked ok for .package but nothing within it. - Phil Williams

People are having to guess how to help you. You should post all relevant code in your question. You are currently missing any code that shows the #CentredContainer element (its important to know the whole HTML structure). Also, what isn't working? In my demo ( jsfiddle.net/KC3yC/2 ) it works no matter what element you click. - Jaspe

I understand. I'll write up an update to help clarify the requirement. - Phil Williams

Puedes probar esto.

if($(event.target).is(function(){
     return ($(this).is(".package") || $(this).find("span").length > 0);
})) {

}

Respondido 02 Feb 12, 02:02

Thanks Shankar but I was unable to get this to work. It only worked against .package div. I tried to increase the specificity to || $(this).is(".giftIconText") but this failed also. - Phil Williams

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.