简体   繁体   中英

Why this jquery code is not working

I have the following code

Html markup

<div>
    <div class="col-md-6">
        <button type="button" class="adddate">Add Date</button>
    </div>
    <div class="col-md-12 form-group">
        <div class="datesaccordion panel-group">

        </div>
    </div>
</div>

<div>
    <div class="col-md-6">
        <button type="button" class="adddate">Add Date</button>
    </div>
    <div class="col-md-12 form-group">
        <div class="datesaccordion panel-group">

        </div>
    </div>
</div>

<div>
    <div class="col-md-6">
        <button type="button" class="adddate">Add Date</button>
    </div>
    <div class="col-md-12 form-group">
        <div class="datesaccordion panel-group">

        </div>
    </div>
</div>

Jquery Code

$(document.body).on("click", ".adddate", addDate);    
function addDate(e) {
    $(e.target).closest(".datesaccordion").append($("<p />").html("test"));
}

Here i am trying to insert the DHTML on .adddate button click. And i want to inter the DHTML in the closest .datesaccordion div from .adddate button. But the jquery code (above mentioned) is not working.

Can anybody please tell me what i am missing??

It should be

$(document).on("click", ".adddate", addDate);
function addDate(e) {
    $(this).parent().next().find(".datesaccordion").append($("<p />").html("test"));
}

Demo: Fiddle

The datesaccordion element is not a ancestor of the button, it is a descdendant of the next sibling of the buttons's parent, so you cannot use .closest() here

Try:

$(document).on("click", ".adddate", addDate);

instead of:

$(document.body).on("click", ".adddate", addDate);

as well as changing your addDate() function to this:

function addDate(e) {
    $(this).parent().siblings('.col-md-12').find('.datesaccordion').append($("<p />").html("test"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM