如何使用jQuery修改动态创建的无序列表



我正在尝试使用jQuery过滤一个无序列表。问题是,列表本身(#jqueryFileTree)是动态加载的,所以我在操作它时遇到了问题http://kilianvalkhof.com/2010/javascript/how-to-build-a-fast-simple-list-filter-with-jquery/):

(function ($) {
    // custom css expression for a case-insensitive contains()
    jQuery.expr[':'].Contains = function (a, i, m) {
        return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
    };
    function listFilter(header, list) { // header is any element, list is an unordered list
        // create and add the filter form to the header
        var form = $("<form>").attr({
            "class": "filterform",
            "action": "#"
        }),
            input = $("<input>").attr({
                "class": "filterinput",
                "type": "text"
            });
        $(form).append(input).appendTo(header);
        $(input)
            .change(function () {
                var filter = $(this).val();
                if (filter) {
                    alert($(list).html());
                    // this finds all links in a list that contain the input,
                    // and hide the ones not containing the input while showing the ones that do
                    $(list).find("a:not(:Contains(" + filter + "))").parent().slideUp();
                    $(list).find("a:Contains(" + filter + ")").parent().slideDown();
                } else {
                    $(list).find("li").slideDown();
                }
                return false;
            })
            .keyup(function () {
                // fire the above change event after every letter
                $(this).change();
            });
    }
    //ondomready
    $(function () {
        listFilter($("#sortable_list_head"), $("#jqueryFileTree"));
    });
}(jQuery));

据我所知,我需要使用.on()方法来侦听ul#jqueryFileTree父级上的事件。问题是,我不想听名单上的任何事件。我所需要做的就是在搜索框上侦听一个事件,它会触发列表上的find方法来过滤它。但由于创建文档时列表不存在,find不起作用。

那么,在不直接对动态创建的元素使用监听器的情况下,我如何使用.fund呢?

提前感谢!

只需传递选择器,而不是jquery对象(在调用它时为空

listFilter($("#sortable_list_head"), "#jqueryFileTree");

由于您不缓存它,但始终执行$(list),因此不会有任何问题。。

尽管您仍然可以将其缓存在change函数中

.change(function () {
    var filter = this.value,
        $list = $(list);
    if (filter) {
        alert($list.html());
        // this finds all links in a list that contain the input,
        // and hide the ones not containing the input while showing the ones that do
        $list.find("a:not(:Contains(" + filter + "))").parent().slideUp();
        $list.find("a:Contains(" + filter + ")").parent().slideDown();
    } else {
        $list.find("li").slideDown();
    }
    return false;
})

最新更新