iT邦幫忙

0

javascript 如何使用新加入的元素

<body>
    <button id="btn">CLICK</button>
    <div id="list"></div>
</ul>
</body>
</html>
<script>
document.getElementById('btn').addEventListener('click',function(){
    var span = document.createElement('span');
    span.setAttribute('class','aaa');
    span.innerHTML = "123";
    document.getElementById('list').insertBefore(span, null);
});
document.getElementById('aaa').addEventListener('click',function(){
    alert(123);
});
</script>

我要如何才能點擊新加入的時可以alert

豬豬人 iT邦新手 4 級 ‧ 2019-07-18 20:25:42 檢舉
span.setAttribute('id','aaa');
class改成id才對
dragonH iT邦超人 5 級 ‧ 2019-07-18 21:16:27 檢舉
可以編輯阿XD
淺水員 iT邦大師 6 級 ‧ 2019-07-19 01:08:11 檢舉
我滿好奇把 script 寫在 html 後面的起源是什麼,這好像不是符合規範的寫法。
https://stackoverflow.com/questions/3037725/is-it-wrong-to-place-the-script-tag-after-the-body-tag
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
marlin12
iT邦研究生 5 級 ‧ 2019-07-18 21:02:56
<html>
<body>
  <button id="add-link">Add link</button>
  <div id="link-container"></div>

  <script>
    document.getElementById('add-link').addEventListener( 'click', () => {
      const node = document.createElement('span');
      node.innerText = 'link';
      node.style.cursor = 'pointer';
      node.addEventListener( 'click', () => alert('Link clicked!') );

      document.getElementById('link-container').appendChild( node );
    });
  </script>
</body>
</html>

我要發表回答

立即登入回答