点击文本触发SweetAlert弹窗及输入验证功能实现咨询
Hey there! Let's walk through setting this up step by step—perfect for a programming beginner to follow along.
First, Load SweetAlert
Before writing any custom code, you need to include the SweetAlert library in your HTML. Add this CDN link right before the closing </body> tag (or in the <head> with the defer attribute):
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
Step 1: Attach Click Event to Your TD Element
We’ll target your <td> element using its ID H and add a click listener. When clicked, this will trigger the input dialog.
Step 2: Show Input Dialog & Validate User Input
SweetAlert’s Swal.fire() returns a promise, which lets us handle the user’s response after they interact with the dialog. We’ll use .then() to check their input and show the correct success/error message.
Full Working Code
Here’s the complete, ready-to-use code:
<!DOCTYPE html> <html> <body> <!-- Your existing TD element --> <td class="gases" title="Hidrógeno" id="H">H</td> <!-- Include SweetAlert library --> <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script> <script> // Wait for the page to fully load before accessing elements document.addEventListener('DOMContentLoaded', function() { // Select the target hydrogen TD element const hydrogenCell = document.getElementById('H'); // Add click event listener hydrogenCell.addEventListener('click', function() { // Launch the input dialog Swal.fire({ title: '¿Cuál es el elemento?', text: 'Introduce el nombre aquí', input: 'text', inputPlaceholder: 'Nombre', }).then((result) => { // Check if the user clicked "Confirm" (not "Cancel") if (result.isConfirmed) { // Clean up input by removing extra spaces const userInput = result.value.trim(); // Validate against the correct answer if (userInput === 'Hidrógeno') { // Show success alert Swal.fire('Correct!', 'You got the answer right!', 'success'); } else { // Show error alert Swal.fire('Incorrect...', 'You failed!', 'error'); } } }); }); }); </script> </body> </html>
Key Details for Beginners
DOMContentLoaded: Makes sure we only access the<td>element after the page has fully loaded, avoiding "element not found" errors.result.isConfirmed: Ensures we only act if the user submitted the input (not canceled the dialog).result.value: Holds the text the user typed into the input field..trim(): Removes accidental leading/trailing spaces from the input, so things like " Hidrógeno " don’t get marked as wrong.
Optional Extra Features
- Case Insensitivity: To accept inputs like "hidrógeno" or "HIDRÓGENO", adjust the validation line to:
if (userInput.toLowerCase() === 'hidrógeno') { - Empty Input Warning: Add this check before validation to handle blank submissions:
if (userInput === '') { Swal.fire('Oops!', 'Please enter a name.', 'warning'); return; // Stop further code execution }
内容的提问来源于stack exchange,提问作者Raúl

