为什么我在使用.childs for.modal后还需要另一个$()才能工作

Why do i need another $() after using .children for .modal to work

本文关键字:另一个 工作 childs modal for 为什么      更新时间:2023-09-26

我想知道为什么要这样做:

$($("body").children("div")[0]).modal('show');

而不是

$("body").children("div")[0].modal('show');

函数.children不返回一个包含节点的列表吗?我是jquery的新手,还没有javascript的经验,所以我只是想知道有什么区别

.modal是一个引导函数,以防有人想知道。

以下是完整性的上下文:

'click .edit': function (e, value, row, index) {
    $.ajax({
        url: "index.php?controller=" + controller + "&action=edit&id=" + row['id'] + "&type=modal",
        success: function (result) {
            if (result !== null) {
                $("body").prepend(result);
                $($("body").children("div")[0]).modal('show');
            } else {
                alert("There was a problem with editing. Please contact a system admin or try again.");
            }
        }
    });
    e.stopPropagation();
},

因为("div")[0]将返回一个dom元素。,它没有关联jquery函数。为了将jquery函数关联到该元素,您需要通过扭曲$() 将其再次转换为jquery元素

另一种选择是使用像这样的eq()操作符,

$("body").children("div:eq(0)").modal('show');

返回的元素是一个javascript DOM元素,它没有被任何jQuery函数包装。因此,您必须用另一个$标记来包裹它。如果您想获得第一个元素,请使用$("body").children("div").first(),这将获得第一个作为jQuery对象的元素,您可以在其中使用所有jQuery函数。

相关文章: