简体   繁体   English

使用jquery添加选项以选择克隆表行内的元素会导致修改克隆元素外的选择选项

[英]Using jquery to add options to select element within cloned table row causes select options outside the cloned element to be modified

I'm trying to use a table row as a template for adding multiple rows. 我正在尝试使用表格行作为添加多行的模板。 I need to clone the row, then update the select elements with some data. 我需要克隆该行,然后使用一些数据更新选择元素。 I hide the table row template before I do the clone, so the selects should not show up for the time being. 在进行克隆之前,我先隐藏了表格行模板,因此暂时不会显示选择内容。

The issue I'm having is that I have other selects defined on the page that are being modified by this process, but when I do the following: 我遇到的问题是,我在页面上定义了其他选择,这些选择正在被此过程修改,但是当我执行以下操作时:

clonedTr.find('select').each(function() {
    console.log($(this));
    ...

it confirms that I am only working with the selects within the cloned table row. 它确认我仅使用克隆表行中的选择。 See this jsfiddle: https://jsfiddle.net/fud4wej2/2/ 看到这个jsfiddle: https ://jsfiddle.net/fud4wej2/2/

I also tried to call rowTemplate.remove() after the clone() , thinking that the issue might have to do with duplicated ids, but to no avail. 我也试着拨打rowTemplate.remove()clone()以为问题可能有重复的ID来办,但无济于事。 Otherwise, to see the top pulldown being displayed correctly - showing Foobar as it's option - comment in the return; 否则,要查看顶部下拉菜单是否正确显示-将Foobar作为其选项-在return;注释return; statement. 声明。

As is -- with $(this).append(option); $(this).append(option); -使用$(this).append(option); commented out -- the top pulldown shows the second entry WB-730-2 from optionsToAdd as its option. 已注释掉-顶部下拉菜单显示optionsToAdd作为选项的第二个条目WB-730-2 If you comment in the final $(this).append(option); 如果您在最后的$(this).append(option);发表评论$(this).append(option); statement, the top pulldown has no options. 语句,顶部下拉列表没有选项。

These lines: 这些行:

var option = $('option');
option.val(optionsToAdd[i]);
option.text(optionsToAdd[i]);

The $('option') function is evaluating that CSS selector in the scope of the whole document, which grabs every option tag on the page. $('option')函数正在评估整个文档范围内的CSS选择器,该选择器将捕获页面上的每个 option标签。 This is causing your problem. 这是造成您的问题。

To fix: 修理:

var option = $('<option>');

This will parse the HTML and create a new option element. 这将解析HTML并创建一个新的option元素。

Another alternative: 另一种选择:

var option = $(document.createElement("option"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM