gpt4 book ai didi

javascript - 点击添加 HTML 元素

转载 作者:行者123 更新时间:2023-11-28 19:05:49 25 4
gpt4 key购买 nike

我被jquery困住了,其中我试图添加动态html元素(单击+),单击(-)也应该将其删除。每个元素应该有唯一的名称和 ID,例如“name_1”、“name_2”...

但这似乎并不符合我的意愿。

这是我的代码:

$(document).ready(function() {
var maxField = 10;
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var fieldHTML = $('.field_wrapper1').html();
var x = 1;
$('.add_button').click(function() {
if (x < maxField) {
x++;
$('.field_wrapper').append('<div class="field_wrapper1" style = "display:none;margin:20px;"><div><strong>*Upload New Contract Copy :</strong><input type="text" name="text_1" id = "text_1" value="" maxlength="50"/><strong><font color="#ff0000">* </font>Upload New Contract Copy :</strong><input type="file" name="pdf_1" id="pdf_1" accept="application/pdf" /><a href="javascript:void(0);" class="remove_button" title="Remove field"><img src="http://www.allintravellocal.com/images/minus_img.jpg"/></a><label for="contract_copy_pdf" class="err" id="err_lbl_contract_copy_pdf"></label></div></div>');
}
});
$(wrapper).delegate('.remove_button', 'click', function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
});
});
<div class="field_wrapper">
<div>
<strong><font color='#ff0000'>* </font>Upload New Contract Copy :</strong>
<input type="text" name="contract_copy_text_1" id="contract_copy_text_1" value="" maxlength="50" />
<strong><font color='#ff0000'>* </font>Upload New Contract Copy :</strong>
<input type="file" name="contract_copy_pdf_1" id="contract_copy_pdf_1" accept="application/pdf" />&nbsp;&nbsp;&nbsp;&nbsp;(*.pdf)
<a href="javascript:void(0);" class="add_button" title="Add field">
<img src="http://www.allintravellocal.com/images/plus_img.jpg" />
</a>
<label for="contract_copy_pdf" class="err" id="err_lbl_contract_copy_pdf"></label>
</div>
</div>

这是我的 fiddle :

Demo

最佳答案

它按预期工作,但需要修改的地方很少:

<强> DEMO

  • You have set display:none to your added element and even though its getting appended its not getting shown in the UI. So just remove that property as below:

$('.field_wrapper').append('<div class="field_wrapper1" style = "margin:20px;">... }

  • Use .on instead of .delegate if you are using jquery.js > 1.7 because As of jQuery 1.7, .delegate() has been superseded by the .on() method according to this and so the below code changes

更改

$(wrapper).on('click','.remove_button', function(e){ 
e.preventDefault();
$(this).parent('div').remove();
x--;
});

关于javascript - 点击添加 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31715557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com