【问题标题】:Adding dynamic form elements jQuery添加动态表单元素jQuery
【发布时间】:2015-12-16 09:58:39
【问题描述】:

我正在尝试使用 jQuery 将动态表单元素添加到我的页面。目前,当用户单击按钮时,我可以添加一个表单元素,但第二个元素没有被添加到它旁边。

我通过在单击按钮时将一些 html 附加到具有特定类的 div 来做到这一点。

我创建了一个 JSfiddle。如您所见,“成分”部分正在起作用,但数量却没有。

https://jsfiddle.net/fe0t3by2/

$('.recipe-ingredients #addNewIngredient').on('click', function () {
        var i = $('.recipe-ingredients .ingredient').size() + 1;
        $('<div class="form-group ingredient"><label class="control-label" for="searchinput">Ingredients</label><div><input id="ingredient_' + i + '" name="ingredients[]" type="text" placeholder="Ingredients" class="form-control input-md"></div></div><a href="javascript:void(0)" class="pure-button pure-u-1-6 pure-button-primary" id="addNewIngredient">Add Ingredient</a></div>').appendTo($('.recipe-ingredients .ingredients'));
        $('<div class="form-group"><label class="control-label" for="buttondropdown">Quantity</label><div class="input-group"><input id="quantity_' + i + '" name="quantity[]" class="form-control" placeholder="Quantity" type="text"><div class="input-group-btn"><button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">Measure<span class="caret"></span></button><ul class="dropdown pull-right"><li><a href="#">Grams</a></li><li><a href="#">Ounces</a></li><li><a href="#">Option three</a></li></ul></div></div>').appendTo($('.recipe-quantities .quantities'));
});

谢谢

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

您在数量 div 上拼错了“recipe-quantities”类。

<div class="col-md-6 recipe-quantites">

改为

<div class="col-md-6 recipe-quantities">

【讨论】:

    【解决方案2】:

    目前,当用户单击按钮时,我可以添加一个表单元素,但第二个元素没有被添加到它旁边。

    使用动态添加的内容,您应该delegate 例如单击文档(包含对象的内容)。

    jQuery documentation .on()

    $(document).on('click', '.recipe-ingredients #addNewIngredient', function () {
    

    JSFiddle demo

    【讨论】:

    • 这是正确的,但我真的怀疑用户是否真的想每次都添加新按钮。感觉很奇怪
    • 完全同意,它一点也不友好。 @Enjoyted
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多