javascript - ไม่พบคุณสมบัติ 'focus' บน 'Element'?
การสร้างการนำทางด้วยแป้นพิมพ์ และพบปัญหาดังต่อไปนี้:
let currentActive = document.activeElement;
if (e.key === "ArrowLeft") {
currentActive.previousElementSibling.focus();
}
โค้ดทำงานตามที่คาดไว้ แต่ TypeScript แจ้งว่า Property 'focus' does not exist on 'Element' - currentActive เป็นแท็ก <img />.
ฉันได้ลองกำหนดค่า currentActive ให้เป็น HTMLElement โดยทำแบบนี้: let currentActive=document.activeElement as HTMLCollectionOf<HTMLElement> แต่ดูเหมือนว่ามันจะไม่ชอบแบบนั้น
ฉันกำลังพลาดอะไรอยู่หรือ?
คำตอบ #1
ฉันขอแนะนำให้ลองอะไรแบบนี้:
let currentActive = document.activeElement;
if (e.key === "ArrowLeft") {
(currentActive.previousElementSibling as HTMLElement)?.focus();
}
โปรดทราบว่าการเชนแบบเลือกได้มีตั้งแต่ TypeScript 3.7
คำตอบ #2
ฉันมีปัญหาเหมือนกันและฉันแก้มันโดยการกำหนดประเภทขององค์ประกอบที่ฉันคาดหวังจาก queryselector ในกรณีของฉันฉันคาดหวังองค์ประกอบ input ดังนั้นฉันจึงทำ:
document.querySelector<HTMLInputElement>(`input[name=${element-name}]`)?.focus()
คำตอบ #3
คุณต้องโน้มน้าว TS ว่า currentActive.previousElementSibling เป็นชนิด HTMLElement
เป็นเคล็ดลับพิเศษ ผมขอแนะนำให้โน้มน้าวตัวเองเช่นกันในการหลีกเลี่ยงเครื่องหมายกากบาทสีแดงบางอย่างในคอนโซลของคุณ บางทีอาจเป็นอะไรทำนอง currentActive?.previousElementSibling?.focus?.();
คำตอบ #4
ใช้ as เพื่อบอก TS ว่านี่คือ HTMLElement:
(currentActive.previousElementSibling as HTMLElement).focus();
