简体   繁体   中英

How to manipulate appended content? Jquery

I'm with Jquery.

I appended html to a div like that:

$('div#byletter').append(createLettersHtml());

The createLettersHtml function creates a list of letters (links) all wrapped in 'div.ln-letters'. Then I want to call a 'onclick' event like that:

$('.ln-letters a').click(function(){

    alert(123);

});

but nothing happens! If I will call onclick on any non-appended html element it works, but it doesn't work with appended content. What do I do wrong?

UPDATE:

Here is full code:

$(document).ready(function(){

$.fn.listnav = function(options) {
        var opts = $.extend({}, $.fn.listnav.defaults, options);
        var letters = ['_', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '-'];
        var firstClick = false;
        opts.prefixes = $.map(opts.prefixes, function(n) { return n.toLowerCase(); });

$('div#byletter').append(createLettersHtml());      

function createLettersHtml() {
                var html = [];
                for (var i = 1; i < 27; i++) {
                    if (html.length == 0) html.push('<a class="all" href="#">ALL</a><a class="_" href="#">0-9</a>');
                    html.push('<a class="' + letters[i] + '" href="#">' + ((letters[i] == '-') ? '...' : letters[i].toUpperCase()) + '</a>');
                }
                return '<div class="ln-letters">' + html.join('') + '</div>' + ((opts.showCounts) ? '<div class="ln-letter-count" style="display:none; position:absolute; top:0; left:0; width:20px;">0</div>' : ''); // the styling for ln-letter-count is to give us a starting point for the element, which will be repositioned when made visible (ie, should not need to be styled by the user)
            }



    };

    $.fn.listnav.defaults = {
        initLetter: '',
        includeAll: true,
        incudeOther: false,
        includeNums: true,
        flagDisabled: true,
        noMatchText: 'No matching entries',
        showCounts: true,
        cookieName: null,
        onClick: null,
        prefixes: []
    };


    $('.ln-letters a').click(function(){

        alert(123);

});

});

you can try using .live . You can hook this up in doc ready. .live works well for appended content.

$(function(){
   $('div.ln-letters a').live('click', function(){
      alert(123);
   });
});

You have to set click evet AFTER you append HTML content. Are you sure you are doing that? Besides, use Firebug or Opera Dragonfly to check if you have any errors in you JS.

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