javascript - 使用 jQuery 从子弹出窗口动态填充父窗口上的选择选项
问题描述
我正在尝试使用从子(弹出)表单调用的 ajax 调用返回的数据填充父窗口上的选择元素上的选项。子窗体通过 window.open 从父窗体调用。
奇怪的是删除选择选项有效;这成功了:
$('#selElement', opener.document).find('option').remove().end();
但如下所示附加,抛出 SCRIPT5022: Exception throwed and not caught。
$('#selElement', opener.document).append($("<option />").val('').text('---Select---'));
我也试过
$('#selElement', opener.window.document).append($("<option />").val('').text('---Select---'));
这是代码:
// the line below works; it removes all of the options from the drop-down
$('#selElement', opener.document).find('option').remove().end();
// the ajax call below returns the right data
$.ajax({
url: 'actions.cfc?method=getOptions&returnFormat=json',
dataType: 'json',
// the value being sent here just limits the options returned in the results
data: {myType: $('#myType').val()},
async:false,
success: function(response) {
// getting the right data back
console.log(response);
// the line below results in SCRIPT5022: Exception thrown and not caught
$('#selElement', opener.document).append($("<option />").val('').text('---Select---'));
// never get this far unless I comment out the line above; then the error is thrown here
for (var i = 0; i < response.DATA.length; i++) {
$('#selElement', opener.document).append($("<option />").val(response.DATA[i][0]).text(response.DATA[i][1]));
}
},
error: function (response) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
}
});
有任何想法吗?
解决方案
用于.map
创建您的选项列表并将其附加到选择标签。
const option = response.DATA.map(item => `<option value='${item[0]}'>${item[1]}</option>`);
$('#selElement', opener.document).append('<select>' + option.join('') + '</select>')
const response = { DATA: [
['Mary', 'Mary'],
['Peter', 'Peter'],
['John', 'John'],
['Abel', 'Abel'],
['Mike', 'Mike']
]}
const option = response.DATA.map(item => `<option value='${item[0]}'>${item[1]}</option>`);
option.unshift('<option>-----Select-----</option>');
function myFunction() {
const div = document.getElementById('test');
div.innerHTML = ('<select>' + option.join('') + '</select>');
}
<button onclick="myFunction()">Try it</button>
<div id="test"></div>
推荐阅读
- angular-cli - 安装 Angular cli 时出错
- rust - 如何在板条箱中的二进制文件和 cdylib 之间共享代码?
- java - 是否可以使用 JUnit Rule ExpectedException 访问“捕获”的异常实例?
- r - R中的@import指令-我们应该把它放在哪个文件以及该文件的哪个位置?
- python - 为什么 Micropython 'const' 不接受浮点值?
- python - 在 SQLAlchemy 中使用声明性基类而不是表对象的区别和好处
- axapta - 在 d365 中的 runbasebatch 类中调用查询
- asp.net-core - 如何在 .NET Core HTTP.sys 上使用 Cloudflare Authenticated Origin Pulls
- html - CSS,HTML - 在检查输入时需要帮助更改子元素的文本并更改图标
- html - 如何制作带有图像的按钮。(如 facebook)