0

我和 Jquery 在一起。

我将 html 附加到这样的 div 中:

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

createLettersHtml 函数创建一个包含在“div.ln-letters”中的字母(链接)列表。然后我想像这样调用“onclick”事件:

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

    alert(123);

});

但什么也没发生!如果我在任何未附加的 html 元素上调用 onclick ,它可以工作,但它不适用于附加的内容。我做错了什么?

更新:

这是完整的代码:

$(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);

});

});
4

2 回答 2

5

您可以尝试使用.live。你可以把它挂在 doc ready 中。.live 适用于附加内容。

$(function(){
   $('div.ln-letters a').live('click', function(){
      alert(123);
   });
});
于 2009-08-16T08:45:11.697 回答
0

您必须在附加 HTML 内容后设置 click evet。你确定你正在这样做吗?此外,使用 Firebug 或 Opera Dragonfly 检查您的 JS 是否有任何错误。

于 2009-08-16T08:44:21.310 回答