将输入从window.open传递到父页面

时间:2015-09-16 19:32:09

标签: javascript html

我创建了一个框架集,其中一个框架使用window.open打开一个弹出窗口。在那个打开的窗口中,我有一个表单来收集用户的输入。输入我试图返回到父级但未通过。任何帮助。 我尝试使用window.opener使用此解决方案:Popup window to return data to parent on close 但未能将getChoice()结果返回到父页面。

框架:

<form>
<button type="button" id="opener" onClick="lapOptionWindow('form.html','', '400','200');">Opinion </button>
</form>

框架js:

function lapOptionWindow(url, title, w, h) {
    var left = (screen.width/2)-(w/2);
    var top = (screen.height/2)-(h/2);
    return window.open(url, title,'toolbar=no,location=no,directories=no, status=no, menubar=no, scrollbars=no,resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
} 

form.html(窗口打开):

<div id="lightbox">
            <strong>Chinese/Portuguese: Chinese<input type="radio" name="chorpor" value="" id="choice1"> Portuguese<input type="radio" name="chororpor" value="" id="choice2"></strong>
            </br><button type="button" id="food" onclick="getChoice()">Submit</button>
    </div>

form.js:

function getChoice() {
        var choice = ""; 
        var choice1 = document.getElementById("choice1 "); 
        choice = choice1.checked == true ? "Chinese" : "Portuguese";
        return choice;
    }

1 个答案:

答案 0 :(得分:8)

这是一个提案(我改变了一些小事,请注意):

parent.html的身体:

<button type="button" onclick="popup('popup.html', '', 400, 200);">Opinion</button>
=&gt;
<span id="choiceDisplay">No choice.</span>

parent.html的JavaScript:

function popup(url, title, width, height) {
  var left = (screen.width/2) - (width/2);
  var top = (screen.height/2) - (height/2);
  var options = '';

  options += 'toolbar=no,location=no,directories=no,status=no';
  options += ',menubar=no,scrollbars=no,resizable=no,copyhistory=no';

  options += ',width='  + width;
  options += ',height=' + height;
  options += ',top='    + top;
  options += ',left='   + left;

  return window.open(url, title, options);
}

function setLang(choice) {
  var languages = {
      'en': 'English',
      'fr': 'French',
      'ch': 'Chinese',
      'por': 'Portugese'
  };

  var choiceMessage = 'You have chosen "' + languages[choice] + '".';

  document.getElementById('choiceDisplay').innerHTML = choiceMessage;
}

popup.html的身体:

<form name="f" onsubmit="sendChoiceAndClose()">
<fieldset><legend>Chinese/Portuguese</legend>

<p><input type="radio" name="lang" value="ch" checked>Chinese</p>
<p><input type="radio" name="lang" value="por">Portuguese</p>
<p><input type="submit" /></p>

</fieldset>
</form>

popup.html的JavaScript:

function sendChoiceAndClose() {
  var form = document.forms['f'];
  var choice = form.lang.value;
  opener.setLang(choice);

  this.close();
}

以下是结果概述:

enter image description here

因此,为了简短说明,从弹出窗口调用opener窗口中定义的JavaScript函数以发回选择信息。

但是要小心,如果调用的JavaScript包含阻塞代码(例如alert(...)),则只有在阻塞代码完成后(即在alert窗口之后,弹出窗口才会关闭)例如关闭)。