Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

วิธีสร้างและเพิ่ม HTML Attribute ด้วย JavaScript

เรียนรู้วิธีสร้างและเพิ่ม HTML Attribute ด้วย JavaScript

สมมติคุณมีปุ่มบนเว็บไซต์ ควร Execute Function เมื่อคลิก แต่ใครบางคนลืมเพิ่ม ID หรือ Class ให้ปุ่ม และคุณไม่มี Access HTML Markup โดยตรงตอนนี้

โชคดี สร้าง Attribute และผูกกับ Button Element ได้ด้วย JavaScript

ต้องทำ 3 สิ่ง:

  • สร้าง Attribute ประเภท id
  • ให้ค่า (ชื่อ)
  • เพิ่ม Attribute+Value ใหม่เข้าไปใน Button Element

HTML Markup

ก่อนอื่น HTML Button ที่ไม่มี ID Attribute (Buhu) จนตอนนี้:

<button>Click me!</button>

JavaScript

Select Button ด้วย querySelector():

const button = document.querySelector('button')

Note:

หากเว็บมีหลายปุ่ม สามารถระบุ Selector ได้โดย Chaining เช่น ปุ่มอยู่ใน Div ที่มี ID หรือ Class Unique:

const button = document.querySelector('.service-section button')

Endnote.

ตอนนี้สร้าง Attribute ประเภท id:

const attribute = document.createAttribute('id')

ให้ค่า (ชื่อ):

attribute.value = `js-button-run-function`

ผูก Attribute ใหม่กับ Button Element:

button.setAttributeNode(attribute)

เสร็จแล้ว!

ตอนนี้ Print Button Variable ใน Console จะเห็น Button ถูก Upgrade:

console.log(button) // output: "<button id='js-button-run-function'>Click me</button>"

ตอนนี้ใช้ JavaScript Select ปุ่มนี้ด้วย Unique ID และสร้าง Function รันเมื่อคลิกได้แล้ว

เพื่อยืนยัน เพิ่มโค้ดนี้ใน JS File:

// Select button via its new id value const buttonRunFunction = document.querySelector('#js-button-run-function') // On click show an alert box buttonRunFunction.addEventListener('click', function() { alert('It works!') })

ถ้าทุกอย่างถูกต้อง ควรเห็น Alert Box บอก "It works!" เมื่อคลิกปุ่ม

โค้ดทั้งหมด:

const button = document.querySelector('button') const attribute = document.createAttribute('id') attribute.value = `js-button-run-function` // Attach new attribute to the button button.setAttributeNode(attribute) // Select button via its id const buttonRunFunction = document.querySelector('#js-button-run-function') // Add click event to the button buttonRunFunction.addEventListener('click', function() { alert('it works!') })