繁体   English   中英

AJAX请求追加到不同的DIV

[英]AJAX request to append to different DIVs

我在页面上附加其他输入字段时遇到问题,每个附加输入字段在附加时也具有jquery代码以附加与它们相关的其他选择框。 基本的html结构如下:

<p id="add_field"> … </p>
<div class="show_sub_categories">
    <div id="sub_cat_1">
    <select class="parent" name="search_category"> … </select>
    <select class="parent" name="sub_category"> … </select>
    </div>
</div>
<div class="show_sub_categories">
    <div id="sub_cat_2">
    <select class="parent" name="search_category"> … </select>
    <select class="parent" name="sub_category"> … </select>
    </div>
</div>

下面的代码会附加选择框,但格式不正确。

$(document).ready(function() {

    //$('#loader').hide();

    $('.parent').livequery('change', function() {
        var div = $(".parent").closest("div").attr("id");
        $(this).nextAll('.parent').remove();
        $(this).nextAll('input').remove();

        $('#' + div).append('<img src="images/system/loader2323.gif" style="float:left" id="loader" alt="" />');

        $.post("get_chid_categories.php", {
            parent_id: $(this).val(),
        }, function(response){

            setTimeout(function () { finishAjax(div, response); }, 400);
        });

        return false;
    });
});

function finishAjax(div, response){
    $('#loader').remove();

    $('#'+div).append(unescape(response));
}

get_chid_categories.php仅包含sub_category框的代码,其内容由传递给它的parent_id确定。

我还有另一个附加函数,它添加了show_sub_categories ,sub_cat_'num'和搜索类别选择框。

页面上的所有内容对于第一个附加项均工作正常,即search_cateogry ,sub_category框和正确的gif位置。 我的问题是,在随后的.show_sub_categories追加中,当将search_category框更改为在上面的代码中运行“ change”功能时,将loader gif和关联的sub_category选择框附加到第一个div 我一辈子都无法理解为什么它仍然会这样做,因为第二个页面所附的search_category框肯定位于<div id="sub_cat_2"> ,第三个搜索类别框位于#sub_cat_3等内。等等,因此在定义div时...

var div = $(".parent").closest("div").attr("id");

... div ID也应该是#sub_cat_2 ,然后可以肯定意味着加载程序gif和sub_category选择框都可以正确地附加在我的<div id="sub_cat_2"> 就像说的那样,目前格式化完全是不固定的,无论进行了多少追加,所有内容都会追加到第一个div#sub_cat_1 )。 请帮忙,我正在撕头发! 威利

自从最初发布此问题以来,我设法定义了div并使用最接近的方式来获得选择框所在的div的名称。

您非常接近:

var pid = $(this).attr('id');

$.post("get_chid_categories.php", {
        parent_id: pid,
    }, function(response){

        setTimeout(function () { finishAjax(pid, response); }, 400);
});

setTimeout接受一个更易于编写的匿名函数。 然后,您可以将当前id传递给所有后续函数,使整个代码更加通用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM