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

How can I disable JavaScript click function if link starts with #?


สำหรับนี้ ใช้ preventDefault() ใน JavaScript โค้ด JavaScript ดังนี้

ตัวอย่าง

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head> <body> <a href="urlLink">Press Me to see logs</a> <a href="urlLink">Press Me to see logs in console</a> <a href="#">Nothing will happen</a> <script>    $(function(){       $("a:not([href='#'])").click(function(event){          event.preventDefault();          console.log("You have pressed me!!!!!");       });    }); </script> </body> </html>

เพื่อรันโปรแกรมข้างต้น ให้บันทึกไฟล์ชื่อ anyName.html(index.html) และคลิกขวาที่ไฟล์ เลือก Open with live server ใน VS code editor

ผลลัพธ์

How can I disable JavaScript click function if link starts with #?

หากคุณคลิกลิงก์สองลิงก์ Press Me to see logs และ Press Me to see logs in console จะได้ผลลัพธ์ในคอนโซล แต่ถ้าคลิกลิงก์ Nothing will happen จะไม่พิมพ์อะไร -

How can I disable JavaScript click function if link starts with #?

ข้างต้น ผมกด Press Me to see logs เพื่อแสดงผลลัพธ์

หากคุณคลิกลิงก์ Nothing will happen จะไม่พิมพ์อะไรเหมือนผลลัพธ์ด้านล่าง -

How can I disable JavaScript click function if link starts with #?