.children(“:第一个children”)-ajax-多个第一个children

.children(":first-child") - ajax - multiple first children?

本文关键字:children 第一个 -ajax-      更新时间:2023-09-26

我有一个简单但奇怪的问题——当我选择.children(":first-child")时,会给出多个结果,一个又一个警报。

//  ...
        $.post(ajaxurl, data, function (response) {
                //alert(response);
                tinymce.get('geqqo-editor-new').setContent('');
                $('#geqqo-modal-new').modal('hide');
                $('#geqqo-modal-new').on('hidden.bs.modal', function (e) {
                    $('#timeline').prepend(response);
                    var new_status = $('#timeline').children(":first-child").attr("id");
                    alert(new_status);
                });
//    ...

如何只选择第一个孩子(即最近附加的孩子),而不是像现在这样选择多个孩子。

尝试使用一个方法而不是on方法,使用:first而不是:first-child

$('#geqqo-modal-new').one('hidden.bs.modal', function (e) {
                    $('#timeline').prepend(response);
                    var new_status = $('#timeline').children(":first").attr("id");
                    alert(new_status);
                });

使用

var new_status = $('#timeline').children(":first").attr("id");

虽然:first只匹配单个元素,但:first-child选择器可以匹配多个元素:每个父元素一个。

此外,您还将同一事件绑定到一个元素两次。你应该使用。.one()方法代替.on

$('#geqqo-modal-new').one('hidden.bs.modal', function (e) {
 /*code here*/
}

.one()将处理程序附加到元素的事件。每个元素每个事件类型最多执行一次处理程序。