选择不追加在动态添加的行上的元素选项
Select element options not appending on dynamically added row
为什么当我单击添加行按钮时,不会触发foo function
dos 中所选值的附加值?
$(document).on("click", '.tdAdd', function () {
//alert($(this).closest('tr').index());
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="button" value="Add Row" class="tdAdd"/></td>';
cols += '<td><input type="button" value="Delete" class="tdAdd"/></td>';
cols += '<td><input type="text" /></td>';
cols += '<td><select class = "t">' + foo($(this).closest('tr').index() + 1) + '</select></td>';
newRow.append(cols);
newRow.insertAfter($(this).closest("tr"));
});
请参阅此小提琴演示。
function foo() {
var select = $('.t')
.append($("<option></option>")
.attr("value", 'one')
.text('One'));
select = $('.t')
.append($("<option></option>")
.attr("value", 'two')
.text('Two'));
}
问题是,您正在尝试将选项添加到当前"tr"的下一行,该行始终是 DOM 中可用的下一行(最初位于当前行旁边的那行 - 橙色行)。要在代码中准备的行中添加选项,您必须首先将其添加到 DOM 中,然后插入选项标记。
对代码的最小更改:
$(document).on("click", '.tdAdd', function () {
//alert($(this).closest('tr').index());
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="button" value="Add Row" class="tdAdd"/></td>';
cols += '<td><input type="button" value="Delete" class="tdAdd"/></td>';
cols += '<td><input type="text" /></td>';
cols += '<td><select class = "t"></select></td>';
newRow.append(cols);
newRow.insertAfter($(this).closest("tr"));
foo($(this).closest('tr').index() + 1);//add options once the newly created 'select' is available in DOM
});
您正在追加 JQuery 对象。我已经提取了 HTML 并附加了它。(见这个答案):
function foo(index) {
var select = $("<option></option>")
.attr("value", 'one')
.text('One')
.prop('outerHTML');
return select;
}
我已经更新了更新的小提琴
http://jsfiddle.net/8r0rdcLf/7/
几个问题,首先是foo()
不返回任何内容,因此您尝试将undefined
连接到字符串中。
接下来,您在foo()
中执行的操作没有意义,因为$('.t')
是具有该类的页面中每个元素的集合。
以下内容将克隆第一个选择,将其值设置为 null,然后返回要添加到字符串中的 html
function foo(index) {
var $select = $('.t:first').clone().val('');
return $select.html(); // return the innerHtml of the select as string
}
演示
为了真正简化整个addRow,您可以克隆整行,重置表单控件的值并附加该克隆...所有这些都不需要任何新字符串
$(document).on("click", '.tdAdd', function () {
var $currentRow = $(this).closest('tr');
var $newRow = $currentRow.clone();
$newRow.find(':input').val('');
$currentRow.after($newRow);
})
相关文章:
- 根据select选项元素将表单重定向到不同的URL
- WebdriverIO waitForExist()选择元素's选定的选项
- 如果类不是一个选项,如何在使用 jQuery 时控制(避免)嵌套 html 元素的样式
- 向html选择元素添加选项
- 我如何为列出的选项卡元素编写一个Protractor测试,它会检查它是否's是否处于活动状态
- 选项卡式元素上的动画CSS转换
- 只有当Angular从资源对象检索数据时,才选择选项元素
- Angular 指令似乎没有使用元素传入的选项执行
- 使用docment.createElement向元素添加选项
- Angular始终选择选择元素中的第一个选项
- 选择不追加在动态添加的行上的元素选项
- 动态更新 JavaScript 和 PHP 中的选择元素选项
- 创建一个 html 页面,其选择元素选项相同
- 获取所有选定元素选项的文本
- 使用jquery.on()方法处理同一元素(选项标记)的两个脚本之间的冲突
- jQuery:保存已选择的select元素选项
- 禁用基于类的选择元素选项
- 在页面加载时设置select元素选项
- 禁用Firefox中弹出的选择元素选项
- 在Bootstrap元素选项中使用引号中的引号