【问题标题】:jQuery not finding elements (or updating class) after AJAX responsejQuery 在 AJAX 响应后找不到元素(或更新类)
【发布时间】:2019-11-27 01:33:05
【问题描述】:

我有很多使用 jQuery.on() 事件的工作函数,它们工作正常 - 但前提是它绑定到一个元素(如“a.my-link”或其他东西)。

这个函数hover,绑定到文档或正文,然后遍历多个具有相同类属性的元素。我已经评论了那些不会触发的行。

  • selectable["holder"]:具有“a.fr-drive-selectable”类的元素
  • 如果选择它会添加“fr-drive-selected”类
  • 如果选择了多个(多个),则添加“fr-drive-selected-b”类

我还有一个仅使用 CTRL 键 + 鼠标选择多个元素的功能 - 它可以工作,因为 on() 函数已绑定到元素...

    /**
     *  Selecting or deselecting all available items (CTRL + ALT + A)
     *
     *  - Selecting: CTRL + ALT + A
     *  - Deselecting: CTRL + ALT + D
     */
    page.$body.on("keydown", function (shortcut) {
        if (shortcut.ctrlKey && shortcut.altKey && shortcut.key === "a") {
            selectable["$holder"].each(function () {
                if (!$(this).children(fdrive["content"]["class"]).hasClass(selectable["multiple"]["class"])) {
                    if (!(items.indexOf(parseInt($(this).attr('data-id'))) > -1)) {
                        addItem(items, $(this)); // WORKS FINE!
                    }

                    addContextMenuOption($(this)); // WORKS FINE!

                    console.log(items); // WORKS FINE!

                    $(this).children(fdrive["content"]["class"]).removeClass(selectable["one"] ["class"]); //NOT WORKING AFTER AJAX
                    $(this).children(fdrive["content"]["class"]).addClass(selectable["multiple"]["class"]); //NOT WORKING AFTER AJAX
                }
            });
        } else if (shortcut.ctrlKey && shortcut.altKey && shortcut.key === "d") {
            selectable["$holder"].each(function () {
                if ($(this).children(fdrive["content"]["class"]).hasClass(selectable["multiple"]["class"]) || $(this).children(fdrive["content"]["class"]).hasClass(selectable["one"]["class"])) {
                    $(this).children(fdrive["content"]["class"]).removeClass(selectable["multiple"]["class"]); //NOT WORKING AFTER AJAX
                    $(this).children(fdrive["content"]["class"]).removeClass(selectable["one"]["class"]); //NOT WORKING AFTER AJAX

                    resetContextMenuOptions(); // WORKS FINE!

                    items = []; // WORKS FINE!

                    console.log("Removed ALL"); // WORKS FINE!
                }
            });
        }

        updateItemCounter(items); // WORKS FINE!
    });

如果没有附加动态数据,该函数将起作用 - 之后,它只删除项目,而不是类(add() 或 remove())。我已经使用控制台打印出元素 - AJAX 之后 each() 中的对象没有“最新”类属性。

我知道问题是事件没有绑定到相关元素,但我需要一个快捷方式来处理页面上的关键事件,而不是元素。


类似的功能(效果很好,因为它使用了元素):

        main_content["$holder"].on('contextmenu', 'a.fr-drive-file-selectable', function (ev) {
            if (!(findItemById(items, $(this).attr("data-id")))) {
                $(this).siblings(selectable["selector"]).children(fdrive["content"]["class"]).removeClass(selectable["multiple"]["class"]);
                $(this).siblings(selectable["selector"]).children(fdrive["content"]["class"]).removeClass(selectable["one"]["class"]);

                //resetContextMenuOptions();

                items = [];

                console.log("Adding one item (RESET)");
                addItem(items, $(this));

                console.log(items);

                $(this).children(fdrive["content"]["class"]).removeClass(selectable["multiple"]["class"]);
                $(this).children(fdrive["content"]["class"]).addClass(selectable["one"]["class"]);
            }
        });

为清楚起见,请查看控制台输出。蓝线表示在 AJAX 更新数据之前在“keydown”事件中找到的元素。之后,jQuery 没有找到任何匹配的元素:“a.fr-drive-file-selectable - 它们在页面上!

Console output

** 附加信息(提供答案后)**


<div id="main-content" class="fr-content">

    <!-- AJAX CHANGES CONTENTS with the same elements, same class etc. (only the inner HTML of the elements is changed (ex. name, picture etc.)  -->

    <div class="fr-drive-file-selectable"><!-- name, picture --></div>
    <div class="fr-drive-file-selectable"><!-- name, picture --></div>
    <div class="fr-drive-file-selectable"><!-- name, picture --></div>
    <div class="fr-drive-file-selectable"><!-- name, picture --></div>
    <div class="fr-drive-file-selectable"><!-- name, picture --></div>

</div>

<script>
    var selectable = {
        $holder: $("a.fr-drive-file-selectable"),
        "class": ".fr-drive-file-selectable"
    }
</script>
<script>
    ...
    request.done(function (response, textStatus, jqXHR) {
        if (response["status"]) {
            $(id).html(response["fragment"]); //Loads only div.fr-drive-file-selectable (using foreach in PHP)

            stopPageLoader();

            adjustSidenavHeight();
        } else {
         ///
        }
    });
    ...
</script>


【问题讨论】:

  • 你需要包含你的 AJAX 函数来检查,因为它似乎正在改变 DOM 元素。
  • 是的,我可以确认确实如此。追加新数据,给出一个类(并不总是)......但就像我写的那样,第二个函数就像一个魅力,只有遍历的函数不是工作。是否使用了旧的 DOM 元素(因为没有直接调用 (this))?

标签: javascript jquery ajax events bind


【解决方案1】:

我没有足够的代表来添加评论。

也许您正在尝试在将元素添加到 DOM 之前对其进行引用。

对于动态元素,请尝试在选择器查询中提及父元素,后跟要访问的元素,如下所示。

$(".parent .dynamic-child").removeClass();

【讨论】:

  • 我回答了我的问题,但我必须承认我没有尝试使用父级...问题是,类或 $holder 被保存为 JS 对象并在整个页面中使用。所以添加父母不是一个好主意。
  • 尝试使用 'console.log[selectable["$holder"]]' 记录 'selectable["$holder"]' 中的值。
  • 检查控制台输出 - 我做到了。使用局部变量或“类”就可以了。
【解决方案2】:

所以就这样……找到了答案。我不知道为什么,如果有人可以稍后澄清。

所以我只是更改了selectable["$holder"] 行并在函数中声明了一个局部变量(检查//DIFF)。

修改后的代码


 page.$body.on("keydown", .... {

   let selector = "a.fr-drive-file-selectable";

   $(this).find(selectable["$holder"]) // DIDNT WORK, works before AJAX updates DOM!
   $(this).find(selector) // works ... why?

   //selectable["$holder"].each(function () { CHANGED TO

   $(this).find(selector).each(function () { // NEW CODE

   ...
}

完整代码

    /**
     *  Selecting or deselecting all available items (CTRL + ALT + A)
     *
     *  - Selecting: CTRL + ALT + A
     *  - Deselecting: CTRL + ALT + D
     */
    page.$body.on("keydown", function (shortcut) {
        let selector = "a.fr-drive-file-selectable";

        if (shortcut.ctrlKey && shortcut.altKey && shortcut.key === "a") {
            $(this).find(selector).each(function () {
                if (!$(this).children(fdrive["content"]["class"]).hasClass(selectable["multiple"]["class"])) {
                    if (!(items.indexOf(parseInt($(this).attr('data-id'))) > -1)) {
                        addItem(items, $(this));
                    }

                    addContextMenuOption($(this));

                    console.log(items);

                    $(this).children(fdrive["content"]["class"]).removeClass(selectable["one"]["class"]);
                    $(this).children(fdrive["content"]["class"]).addClass(selectable["multiple"]["class"]);
                }
            });
        } else if (shortcut.ctrlKey && shortcut.altKey && shortcut.key === "d") {
            $(this).find(selector).each(function () {
                if ($(this).children(fdrive["content"]["class"]).hasClass(selectable["multiple"]["class"]) || $(this).children(fdrive["content"]["class"]).hasClass(selectable["one"]["class"])) {
                    $(this).children(fdrive["content"]["class"]).removeClass(selectable["multiple"]["class"]);
                    $(this).children(fdrive["content"]["class"]).removeClass(selectable["one"]["class"]);

                    resetContextMenuOptions();

                    items = [];

                    console.log("Removed ALL");
                }
            });
        }

        updateItemCounter(items);
    });

【讨论】:

  • 这也有一个技巧。使用 setTimeout() 并且它可以工作,而无需声明局部变量或更改调用。我不推荐它。
猜你喜欢
  • 2021-06-09
  • 2014-05-09
  • 2013-12-15
  • 1970-01-01
  • 1970-01-01
  • 2014-01-09
  • 2021-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多