0

我正在尝试编写一个动态表单,您可以在其中向车辆添加多个引擎。这是一个获取表单 html 的 get 方法,将其添加到 DOM,然后应用 typeahead 行为:

$.get("/editor/engineForm", function(formHtml) {
    $("#engineZone").append(formHtml);

    form = $("form.engine:last");

    $(form).find("#sBrand").typeahead({
        remote: "/editor/engineModelBrand"
    });

    $(form).find("#sModel").typeahead({
        remote: {
            replace : function() {
                sBrand = $(form).find("#sBrand").val();
                console.log("Brand :" + sBrand);
                return "/editor/engineModelModel?sBrand=" + sBrand
            }
        }
    });
});

注意级联的 typeahead 完成: sModel.typeahead.remote 使用 sBrand 的值进行请求。

问题是当我有多种形式时:

$(form).find("#sBrand").val();

返回上次创建的输入#sBrand 的值,而不是与当前输入#sModel 对应的值。

这是用于说明的Html代码:

<div class="engine">

    <form action="/editor/engineSave" method="GET" class="engine">  

        <div class="clearfix  " id="sBrand_field">
            <label for="sBrand">sBrand</label>
            <div class="input">
                <input type="text" id="sBrand" name="sBrand" value="" class="sBrand">
            </div>
        </div>

        <div class="clearfix  " id="sModel_field">
            <label for="sModel">sModel</label>
            <div class="input">
                <input type="text" id="sModel" name="sModel" value="" class="sModel">
            </div>
        </div>

    </form>

</div>

<div class="engine">

    <form action="/editor/engineSave" method="GET" class="engine">

        <div class="clearfix  " id="sBrand_field">
            <label for="sBrand">sBrand</label>
            <div class="input">
                <input type="text" id="sBrand" name="sBrand" value="" class="sBrand">
            </div>
        </div>

        <div class="clearfix  " id="sModel_field">
            <label for="sModel">sModel</label>
            <div class="input">
                <input type="text" id="sModel" name="sModel" value="" class="sModel">
            </div>
        </div>

    </form>
</div>

如何让 jquery 找到正确的输入?

我试过了 :

$(this).closest("div").find("#sBrand").val();

$(this).find("#sBrand").val();
4

1 回答 1

0

尝试这个:

$(form).find("#sModel").each(function (index, elem) {
    $(elem).typeahead({
        remote: {
            replace: function () {
                sBrand = $(elem).closest(".engine").find("#sBrand").val();
                console.log("Brand :" + sBrand);
                return "/editor/engineModelModel?sBrand=" + sBrand
            }
        }
    });
});
于 2013-11-09T13:42:03.390 回答