在JavaScript中创建具有按钮的新窗口

在JavaScript中创建具有按钮的新窗口,javascript,html,Javascript,Html,嘿,我现在正在尝试学习JavaScript,我希望能够在我用JavaScript创建的页面上创建一个按钮,但它总是将按钮添加到index.html。请注意,我正在运行这个WebStorm IDE,并且没有URL/不知道要为窗口放置什么。正因为如此,才打开(___;) 它成功地创建了一个新窗口说“你好”,但没有按钮 var myWindow=window.open(''); myWindow.document.write('Hello'); var button=myWindow.document

嘿,我现在正在尝试学习JavaScript,我希望能够在我用JavaScript创建的页面上创建一个按钮,但它总是将按钮添加到index.html。请注意,我正在运行这个WebStorm IDE,并且没有URL/不知道要为窗口放置什么。正因为如此,才打开(___;)

它成功地创建了一个新窗口说“你好”,但没有按钮

var myWindow=window.open('');
myWindow.document.write('Hello');
var button=myWindow.document.createElement("newbutton");
button.onclick= function(){
  alert("blabla");
};
var buttonParent= myWindow.document.getElementById("buttonParent");
buttonParent.appendChild(button)

看起来您正在创建一个名为myWindow的新窗口,并向它写入文本hello。但是,id为“buttonParent”的容器并不位于新窗口中,而是位于index.html所在的文档中

试试这个:

var newDiv = document.createElement("div");      
newDiv.id = "newButtonParent" //make sure you pick a unique id      
myWindow.document.appendChild(newDiv);    
var buttonParent= myWindow.document.getElementById("newButtonParent");     
buttonParent.appendChild(button);
编辑:修正了一个打字错误。发件人:

var buttonParent= myWindow.document.getElementById("buttonParent");    


ID为buttonParent的元素是何时创建的?如果这是您的整个代码段,那么您首先也需要创建该元素,否则在新窗口中找不到任何内容,这意味着无法正常工作

另外需要注意的是,
alert
window
对象的一个属性,因此只需调用
alert(“!”)
即可将警报附加到主窗口。您需要将其称为
myWindow.alert(“!”)
以使其在新窗口上启动

此外,还需要一个标记名,所以如果您想要默认的按钮行为,它应该是

myWindow.document.createElement('button');
这里有一个有效的例子。我已经将container元素的背景设置为红色,以便您可以看到它在那里

-(单击“运行”按钮。)

myWindow.document.createElement('button');
var w = window.open(''),
button = w.document.createElement('button');
button.innerHTML = 'My Button';

button.addEventListener('click', function () {
  w.alert('!');
});

var container = w.document.createElement('div');
container.id = 'buttonParent';
container.style.background = 'red';

w.document.body.appendChild(container);
container.appendChild(button);