Pregunta

There are several posts dealing with on() and DOM elements added through JavaScript, but none see to apply to my situation.

After <li class="prepend"><a href="#">x</a></li> is prepended inside a <ul>, I can't seem to attach events to it.

JS:

$('.categories > li a').on('click', function(event){
    event.preventDefault();
    if ($(this).parent().is('.more')) {
        $(this).siblings('ul').prepend('<li class="back"><a href="#">&lt; ' + $(this).html() + '</a></li>')
    }  else if ($(this).parent().is('.back')) {
        console.log('it worked')
    }
})

HTML:

<ul class="categories">
    <li class="selected">
        <a href="#">1 Featured</a>
    </li>
    <li>
        <a href="#">1 Popular Genres</a>
    </li>
    <li class="more">
        <a href="#">1 My Rooms &gt;</a>
        <ul>
            <li><a href="#">2 Tristique Cras</a></li>
            <li><a href="#">2 Porta Etiam &gt;</a></li>
            <li><a href="#">2 Mattis Tortor</a></li>
            <li class="more">
                <a href="#">2 Cras Fermentum &gt;</a>
                <ul>
                    <li><a href="#">3 Tristique Cras</a></li>
                    <li><a href="#">3 Porta Etiam</a></li>
                    <li><a href="#">3 Mattis Tortor</a></li>
                    <li><a href="#">3 Cras Fermentum</a></li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

Even this simple event won't see clicks to elements with class .back

$('a').on('click', function(event){
    event.preventDefault();
    console.log(this);
})
¿Fue útil?

Solución

Watch this: http://jsfiddle.net/lughino/8uzgd/

in order to capture the elements that are created after the page loads, you need to call on method in this way:

$(document).on('click', '.categories > li a', function(event){

To learn more take a look at the documentation

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top