【JavaScript】JS地下城-1F-9×9乘法表

【JavaScript】JS地下城-1F-9×9乘法表

1F-9×9乘法表Link to this section

wp-image-176

連結Link to this section

Demo

Code

使用語言Link to this section

HTML、CSS、JavaScript

BOSS 弱點Link to this section

  1. 【特定技術】需使用 JS for 迴圈技巧,裡頭數字不能直接寫在 HTML 上,需使用 JS 印出。
  2. 需使用 HTML、CSS、JS 技術
  3. 介面需與設計稿一致

技巧Link to this section

js
function getNum() {
  let str = ''
  // 第一個for迴圈-當前數字
  for (let i = 2; i < 10; i++) {
    str += '<div class="card">'
    str += '<ul>'
    str += `<li class="big-num">${i}</li>`
    // 第二個for迴圈-要乘上的數字
    for (let a = 1; a < 10; a++) { str += `<li>${i} x ${a} = ${i * a}</li>` }

    str += '</ul>'
    str += '</div>'
  }
  // 用insertAdjacentHTML插入str,
  // beforeend指定插入位置在元素結束前子元素結束後
  document.getElementById('wrap').insertAdjacentHTML('beforeend', str)
}
getNum()

關於 insertAdjacentHTMLLink to this section

可以在不刪除子元素的狀態下,像 innerHTML 一樣插入內容

語法

js
element.insertAdjacentHTML(position, text)

指定 position 位置

html
<!-- beforebegin -->
<element>
  <!-- afterbegin -->
  <child>Text</child>
  <!-- beforeend -->
</element>
<!-- afterend -->

追加:如果想要清空元素Link to this section

如果想要清空元素,比起 innerHTML ,用 textContent 的方法就效能上來說比較好。

js
document.getElementById('foo').textContent = ''

追加:如果想要插入HTML元素 insertAdjacentElementLink to this section

如果想要插入元素而不是字串的時候,也有一個東西叫insertAdjacentElement

使用方法基本上跟 insertAdjacentHTML 一樣。

js
const contentBlock = document.getElementById('contentBlock')
const insetElement = document.createElement('b')

insetElement.textContent = 'Test:'

contentBlock.insertAdjacentElement('afterbegin', insetElement)

參考資料Link to this section

innerHTML より insertAdjacentHTML を使う

Tags: