Soy básicamente un principiante en el mundo de la programación. Entonces, actualmente me enfrento a un problema que no entiendo de qué manera debo buscar esta solución. Así que estoy aquí para ayudar. Espero que alguien pueda ayudarme. Realmente necesito esta solución.
<!DOCTYPE html> <html lang="en"> <head> <title>Game1</title> </head> <body> <p id="p1">Lorem ipsum dolor sit amet.</p> <script src="script.js"></script> </body> </html> <!DOCTYPE html> <html lang="en"> <head> <title>Game2</title> </head> <body> <p id="p2">Lorem ipsum dolor sit amet consectetur adipisicing elit. Nobis, quis!</p> <script src="script.js"></script> </body> </html> (function() { const p1 = document.getElementById('p1'); const textChange1 = () => { p1.innerHTML = 'textChange 1'; } p1.addEventListener('click', textChange1); })(); (function() { const p2 = document.getElementById('p2'); const textChange2 = () => { p2.innerHTML = 'textChange 2'; } p2.addEventListener('click', textChange2); })();Así que quiero ejecutar este archivo script.js tanto en Game1.html como en Game2.html.
¡Pero está causando un error! [Texto] https://i.ibb.co/BPVBv4N/html.jpg en Game1.html
script.js:15 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') at script.js:15:8 at script.js:16:3en Juego2.html
script.js:6 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') at script.js:6:8 at script.js:7:3Quiero usar un archivo de script. Cuando game1.html acceda, quiero que game1.html acceda solo al código que incluye id='p1'; y cuando es game2.html, quiero que acceda solo a la parte de js que incluye id='p2'; ¿Cómo puedo lograr esto, que el html use solo la parte de js que se necesita, no las demás?
al igual que usamos un css en múltiples html.
nota: solo quiero usar un archivo js, ningún otro archivo sub-js. Gracias.
Verifique el elemento antes de ejecutarlo, envuelva sus funciones en algo como esto:
if (document.getElementById('p1') !== null){ //p1 exists, continue } if (document.getElementById('p2') !== null){ //p2 exists, continue }Dado que el elemento con id p2 no existe en su primer archivo HTML, devuelve indefinido. Es por eso que llamar a p2.addEventListener no funcionará, porque addEventListener no está indefinido.
Para solucionar esto, puede agregar una verificación de si el elemento existió y solo continuar si existe.
(function() { const p1 = document.getElementById('p1'); if(!p1) return; // Just replace it with p2 for the other part const textChange1 = () => { p1.innerHTML = 'textChange 1'; } p1.addEventListener('click', textChange1); })();Para usar el mismo script.js para las 2 páginas, debe verificar si el elemento que está seleccionando existe en esa página antes de agregar addEventListener como en el ejemplo a continuación.
(function() { const p1 = document.getElementById('p1'); if(p1){ const textChange1 = () => { p1.innerHTML = 'textChange 1'; } p1.addEventListener('click', textChange1); } })(); (function() { const p2 = document.getElementById('p2'); if(p2){ const textChange2 = () => { p2.innerHTML = 'textChange 2'; } p2.addEventListener('click', textChange2); } })();