samedi 27 juin 2015

jquery, click on class not working when page loads from .load [duplicate]

This question already has an answer here:

If I execute this from a single page (all the code on the same page) it works as expected... However, I want to have the "filter" code in a seperate file, so I can reuse it on other pages....

THIS WORKS (the code that errors is below)

<!DOCTYPE html><html lang="en" ><head></head><body>

<table class="table table-bordered table-condensed"  >
    <tr>
        <td><a class="alphaFilterLink" data="A" >A</a></td>
        <td><a class="alphaFilterLink" data="B" >B</a></td>
        <td><a class="alphaFilterLink" data="C" >C</a></td>
        <td><a class="alphaFilterLink" data="D" >D</a></td>
    </tr>
</table>

</body></html>

<!-- script references -->
<script src="resources/js/jquery.min.js" ></script>
<script src="resources/js/bootstrap.min.js" ></script>

<script>        
    // Filter By Letter
    $( '.alphaFilterLink' ).click( function() {
        var x = $( this ).attr( 'data' );
        alert( 'we are responding to the click of a alphaFilterLink ' + x );
    });
</script>

THIS DOES NOT WORK: (and nothing shows in console)

<!DOCTYPE html><html lang="en" ><head></head><body>

<div id="filter"></div>

</body></html>

<!-- script references -->
<script src="resources/js/jquery.min.js" ></script>
<script src="resources/js/bootstrap.min.js" ></script>

<script>
    $( '#filter' ).load( 'templates/filter.html', function( response, status, xhr ) {
        $( '#filter' ).slideDown( 3000 ).fadeIn( 1000 ); // slide it down
        if ( status == 'error' ) {
            var msg = 'Sorry but there was an error loading the filter page: ';
            $( '#filter' ).html( msg + xhr.status + ' ' + xhr.statusText );
        }
    });

    // Filter By Letter
    $( '.alphaFilterLink' ).click( function() {
        var x = $( this ).attr( 'data' );
        alert( 'we are responding to the click of a alphaFilterLink ' + x );
    });
</script>

templates/filter.html

<table class="table table-bordered table-condensed"  >
    <tr>
        <td><a class="alphaFilterLink" data="A" >A</a></td>
        <td><a class="alphaFilterLink" data="B" >B</a></td>
        <td><a class="alphaFilterLink" data="C" >C</a></td>
        <td><a class="alphaFilterLink" data="D" >D</a></td>
    </tr>
</table>

Aucun commentaire:

Enregistrer un commentaire