javascript - 动态添加/删除输入行 javascript,jquery
问题描述
动态添加/删除输入行无法正常工作。这些行是使用 add 函数创建的,但没有正确删除。基本上删除函数调用不起作用。
$(document).ready(function(){
var counter = 1; //initlal text box count
$("#addButton").click(function () {
if(counter > 3){
alert("Only 3 textboxes allowed");
return false;
}
var selectfield = $('#selectcolumnlist option:selected').val();
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv');
newTextBoxDiv.after().html('<label>'+ selectfield + ' : </label>' + '<input type="text" name="textbox_' + selectfield + '" id="textbox_'+selectfield+'" placeholder="' + selectfield + '" value="" /><input type="button" value="Remove Button" class="remove_this" id="removeid" />');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
alert(counter);
});
$("#removeid").click(function() {
alert("i'm in");
});
}
解决方案
假设您以正确的方式创建元素,我的意思是,使用唯一 ID,您应该使用event-delegation
:
// This example selects the element with the class
// .removeid (here you need to set a specific class) or set something unique
// per new dynamically created element.
$("#TextBoxesGroup").on('click', '.remove_this', (function() {
alert("i'm in");
}));
推荐阅读
- http - 来自让我们使用后端 api 和前端 SPA 的 nginx 代理加密的 SSL 证书
- html - 如果第二个是动态的,如何将一个 div 的高度调整为另一个 div 的高度
- angular - 多条路线在 Angular 10 延迟加载模块中不起作用
- c++ - 在被调用方站点强制进行重载选择
- karate - 具有 browserstack iphone 支持的空手道 UI 框架
- r - ggplot层在第一次放置时会破坏顺序
- reactjs - 反应useEffect没有运行
- java - 插件 'org.springframework.boot:spring-boot-maven-plugin:' 未找到
- c++ - 我可以“隐藏”在 C++ 的头文件中定义的任何内容吗
- typescript - Typescript + Webpack 库生成“ReferenceError: self is not defined”