首页 > 解决方案 > 使用 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);
    }
});

有任何想法吗?

标签: javascriptjquerydom

解决方案


用于.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>


推荐阅读