简体   繁体   English

我不明白 javascript 中的创建元素 function

[英]I didn't understand the create element function in javascript

Suppose I write following JavaScript code:-假设我写了以下 JavaScript 代码:-

//Line1

document.createElement("button");

//Line2
document.createElement("button").onclick="func();

Now question is what will happen next Scenario 1:- JavaScript will create two buttons.现在的问题是接下来会发生什么场景 1:- JavaScript 将创建两个按钮。 Scenario 2:- JavaScript will create 1 button with onclick attribute.场景 2:- JavaScript 将创建 1 个具有 onclick 属性的按钮。 If scenario 2 is true how JavaScript created attribute in 2nd line without calling getelement function.means how JavaScript was knowing that I am still working on previous button and not asking to create a new button.如果创建方案 2 为真,JavaScript 如何在第二行创建属性而不调用 getelement function。这意味着 JavaScript 如何知道我正在使用新按钮并且不要求使用上一个按钮。

I am a beginner and this is my first time posting question so forgive for mistakes.我是初学者,这是我第一次发布问题,请原谅错误。

The createElement function creates a new element and returns it. createElement function 创建一个新元素并将其返回。

So here you will create 2 different buttons (one for each time you called the function).因此,您将在这里创建 2 个不同的按钮(每次调用该函数时一个)。

You can see that the second time you are calling createElement, it is not the same as the first one.可以看到,第二次调用 createElement 时,与第一次不一样。 You can test that like this to make sure:您可以像这样测试以确保:

a = document.createElement("button")
b = document.createElement("button")
a == b // false

This will return false because they are different.这将返回 false,因为它们是不同的。

So as a and b are both elements created, you can call因此 a 和 b 都是创建的元素,您可以调用

a.onclick = function() {}
// or
b.onclick = function() {}

Both the lines when executed, creates two different elements and returns them.这两行在执行时都会创建两个不同的元素并返回它们。 Note that they are not yet added to the DOM and since the returned elements are not captured in any variable, they can't be added to DOM later.请注意,它们尚未添加到 DOM 中,并且由于返回的元素未在任何变量中捕获,因此以后无法将它们添加到 DOM 中。

Here's the correct way of creating and adding a button in the DOM:下面是在 DOM 中创建和添加按钮的正确方法:

 var button = document.createElement('button'); button.innerText = "Button1"; button.onclick = handler; document.getElementById('parent').appendChild(button);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM