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

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

问题描述:

嘿,我正试图学习JavaScript,我希望能够在JavaScript中创建的页面上创建按钮,但它总是将该按钮添加到index.html中。请注意我正在使用WebStorm IDE,因此没有URL /不知道要为window.open(____)放置什么。

Hey Im trying to to learn JavaScript at the moment, and I want to be able to create a button on a page that I created in JavaScript, but it always adds the button to index.html instead. Please note I am running this off of WebStorm IDE and don't have a URL/ dont know what to put for window.open(____) because of that.

它成功创建了一个新窗口,显示Hello,但没有按钮。

It successfully creates a new window saying "Hello", but there is no button.

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)


是创建了ID buttonParent 的元素吗?如果这是你的整个片段,你首先需要创建该元素,否则 .getElementById 不会在新窗口中找到任何内容,即 .appendChild 将无法正常工作。

When was the element with the ID buttonParent created? If this is your entire snippet, you'd first need to create that element as well, otherwise .getElementById isn't going to find anything in the new window, meaning .appendChild won't work properly.

另外要注意的是 alert 窗口的一个属性对象,所以只需调用 alert('!')就会在主窗口中添加警报。您需要将它称为 myWindow.alert('!'),以便在新窗口中触发它。

The other thing to note is that alert is a property of the window object, so just calling alert('!') will attach the alert the the main window. You need to call it as myWindow.alert('!') to have it fire on the new window.

另外, document.createElement 需要一个标签名称,所以如果你想要默认的按钮行为,它应该是

Also, document.createElement takes a tag name, so if you want default button behaviour it should be

myWindow.document.createElement('button');

下面是一个工作示例。我已经将容器元素的背景设置为红色,以便您可以看到它在那里。

Here's a working example. I've set the background of the container element to red so you can see it is there.

DEMO - (点击运行按钮。)

DEMO - (Click the run 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);