“如何在元素创建之前运行的脚本中“访问”新创建的 div 元素?”

huangapple go评论65阅读模式
英文:

How "access" a newly created div element in a script which ran before the element creation?

问题

假设我有一个HTML页面

<html>
<body>
<button onclick="add_product()">
ADD
</button>
<script type="text/javascript" src="static/script1.js"></script>
<script type="text/javascript" src="static/script2.js"></script>
</body>
</html>


其中 `script1.js` 是

function add_product(){
const add_product_div = document.createElement("div");
add_product_div.id = "add_product";
add_product_div.className = "draggable_box";
add_product_div.innerHTML="<h1> hey </h1> <p> whatevea </p> ";
document.body.appendChild(add_product_div);
}


现在,我该如何在 `script2.js` 中访问新创建的 `draggable_box` div?

div = document.getElementsByClassName("draggable_box");
console.log(div)

英文:

Suppose I have an html page

&lt;html&gt; 
	&lt;body&gt;
      &lt;button onclick=&quot;add_product()&quot;&gt;
		ADD 
	 &lt;/button&gt;
	 &lt;script type=&quot;text/javascript&quot; src=&quot;static/script1.js&quot;&gt;&lt;/script&gt;
	 &lt;script type=&quot;text/javascript&quot; src=&quot;static/script2.js&quot;&gt;&lt;/script&gt;
    &lt;/body&gt;
&lt;/html&gt;

where script1.js is

function add_product(){
    const add_product_div = document.createElement(&quot;div&quot;);
    add_product_div.id = &quot;add_product&quot;;
    add_product_div.className = &quot;draggable_box&quot;;
    add_product_div.innerHTML=&quot;&lt;h1&gt; hey &lt;/h1&gt; &lt;p&gt; whatevea &lt;/p&gt; &quot;;
    document.body.appendChild(add_product_div);
}

Now how can I access the newly created div draggable_box in script2.js

div = document.getElementsByClassName(&quot;draggable_box&quot;);
console.log(div)

console.log(div)
Gives a empty list as script2.js had already run before I added the element draggable_box.

I am new to web development! Essentially I want to use script2.js to make all the div I create draggable, I know how to do this when the script is run after the div is created. Please suggest the correct way to do this!

答案1

得分: 2

以下是您要翻译的内容:

There are many ways to handle this. Here are a few. The first would be most common and require the least effort. The other two would be somewhat unusual and I'm mostly including them to illustrate that there's more than one way to do this.

You could have your add_product function return the new div so the caller can do other stuff with it after it's created:

function add_product(){
    const add_product_div = document.createElement("div");
    add_product_div.id = "add_product";
    add_product_div.className = "draggable_box";
    add_product_div.innerHTML="<h1> hey </h1> <p> whatevea </p> ";
    document.body.appendChild(add_product_div);
    return add_product_div; // return the new div
}

function onProductButtonClick () {
  const div = add_product(); // append a new div and get a reference to it
  console.log(div); // do other stuff with the new div
}

const button = document.getElementById('addProductButton');
button.addEventListener('click', onProductButtonClick)

You could have add_product emit an event that other code can listen for:

function add_product() {
  const add_product_div = document.createElement("div");
  add_product_div.id = "add_product";
  add_product_div.className = "draggable_box";
  add_product_div.innerHTML = "<h1> hey </h1> <p> whatevea </p> ";
  document.body.appendChild(add_product_div);

  // emit a 'productadded' event
  document.body.dispatchEvent(new CustomEvent(
    'productadded',
    {
      detail: {
        target: add_product_div
       }
     }
   ));
}

const button = document.getElementById('addProductButton');
button.addEventListener('click', add_product);

function onAdded(e) {
  console.log(e.detail.target);
}

// listen for 'productadded' events
document.body.addEventListener('productadded', onAdded);

You could have a MutationObserver that alerts you when nodes get added to the DOM:

function add_product() {
  const add_product_div = document.createElement("div");
  add_product_div.id = "add_product";
  add_product_div.className = "draggable_box";
  add_product_div.innerHTML = "<h1> hey </h1> <p> whatevea </p> ";
  document.body.appendChild(add_product_div);
}

function initObserver() {
  const observer = new MutationObserver((mutationList) => {
    for (const mutation of mutationList) {
      console.log(mutation.addedNodes[0]);
    }
  });

  observer.observe(document.body, {
    childList: true
  });
}

window.addEventListener('load', initObserver);

const button = document.getElementById('addProductButton');
button.addEventListener('click', add_product);

希望这对您有所帮助。如果您有任何其他问题,请随时提问。

英文:

There are many ways to handle this. Here are a few. The first would be most common and require the least effort. The other two would be somewhat unusual and I'm mostly including them to illustrate that there's more than one way to do this.

You could have your add_product function return the new div so the caller can do other stuff with it after it's created:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function add_product(){
    const add_product_div = document.createElement(&quot;div&quot;);
    add_product_div.id = &quot;add_product&quot;;
    add_product_div.className = &quot;draggable_box&quot;;
    add_product_div.innerHTML=&quot;&lt;h1&gt; hey &lt;/h1&gt; &lt;p&gt; whatevea &lt;/p&gt; &quot;;
    document.body.appendChild(add_product_div);
    return add_product_div; // return the new div
}

function onProductButtonClick () {
  const div = add_product(); // append a new div and get a reference to it
  console.log(div); // do other stuff with the new div
}

const button = document.getElementById(&#39;addProductButton&#39;);
button.addEventListener(&#39;click&#39;, onProductButtonClick)

<!-- language: lang-html -->

&lt;button id=&quot;addProductButton&quot;&gt;Add Product&lt;/button&gt;

<!-- end snippet -->


You could have add_product emit an event that other code can listen for:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function add_product() {
  const add_product_div = document.createElement(&quot;div&quot;);
  add_product_div.id = &quot;add_product&quot;;
  add_product_div.className = &quot;draggable_box&quot;;
  add_product_div.innerHTML = &quot;&lt;h1&gt; hey &lt;/h1&gt; &lt;p&gt; whatevea &lt;/p&gt; &quot;;
  document.body.appendChild(add_product_div);

  // emit a &#39;productadded&#39; event
  document.body.dispatchEvent(new CustomEvent(
    &#39;productadded&#39;,
    {
      detail: {
        target: add_product_div
       }
     }
   ));
}

const button = document.getElementById(&#39;addProductButton&#39;);
button.addEventListener(&#39;click&#39;, add_product);

function onAdded(e) {
  console.log(e.detail.target);
}

// listen for &#39;productadded&#39; events
document.body.addEventListener(&#39;productadded&#39;, onAdded);

<!-- language: lang-html -->

&lt;button id=&quot;addProductButton&quot;&gt;Add Product&lt;/button&gt;

<!-- end snippet -->


You could have a MutationObserver that alerts you when nodes get added to the DOM:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function add_product() {
  const add_product_div = document.createElement(&quot;div&quot;);
  add_product_div.id = &quot;add_product&quot;;
  add_product_div.className = &quot;draggable_box&quot;;
  add_product_div.innerHTML = &quot;&lt;h1&gt; hey &lt;/h1&gt; &lt;p&gt; whatevea &lt;/p&gt; &quot;;
  document.body.appendChild(add_product_div);
}


function initObserver() {
  const observer = new MutationObserver((mutationList) =&gt; {
    for (const mutation of mutationList) {
      console.log(mutation.addedNodes[0]);
    }
  });

  observer.observe(document.body, {
    childList: true
  });
}

window.addEventListener(&#39;load&#39;, initObserver);

const button = document.getElementById(&#39;addProductButton&#39;);
button.addEventListener(&#39;click&#39;, add_product);

<!-- language: lang-html -->

&lt;button id=&quot;addProductButton&quot;&gt;Add Product&lt;/button&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月17日 11:42:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76268414.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定