jQuery在typeahead“block”之外找到元素

时间:2013-11-09 13:31:48

标签: jquery typeahead

我正在尝试编写一个动态表单,您可以在其中添加多个引擎。这是一个get方法,它可以检索html格式,将其添加到DOM中,然后应用预先输入行为:

$.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
            }
        }
    });
});

注意级联预先完成: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();

1 个答案:

答案 0 :(得分: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
            }
        }
    });
});