.children(":first-child") - ajax - 多个第一个孩子?

时间:2014-04-25 04:23:57

标签: javascript jquery ajax

我有一个简单而奇怪的问题 - 当我选择.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);
                });
//    ...

如何仅选择第一个孩子(即最近添加的孩子)而不是多个孩子,例如它正在做的事情。

2 个答案:

答案 0 :(得分:1)

尝试使用one method代替方法而不是: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);
                });

答案 1 :(得分:0)

使用

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()将处理程序附加到元素的事件。每个事件类型的每个元素最多执行一次处理程序。