如何在Twig中使用jQuery实现点击显示隐藏指定链接功能
Got it, let's walk through how to implement this functionality in your Twig template step by step. Here's a straightforward solution:
First, set up your link structure in Twig. Make sure your elements have the exact IDs you mentioned:
{# Your Twig template content #} <a href="#" id="Ajouter">Ajouter</a> <a href="#" id="supprimer">Supprimer</a>
Step 1: Hide the "Supprimer" link by default
You can do this with CSS (either in an external stylesheet or inline in your template):
#supprimer { display: none; }
Alternatively, you can hide it via jQuery on page load (we'll cover that option later if you prefer).
Step 2: Add the jQuery logic
First, ensure jQuery is loaded in your template (use a CDN or local file). Then add this script block, ideally at the end of your <body> tag to guarantee the DOM is fully loaded before running the code:
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <script> $(document).ready(function() { // Bind click event to the "Ajouter" link $('#Ajouter').on('click', function(e) { e.preventDefault(); // Stop the default link behavior (adjust if you need the link to navigate) // Show the hidden "Supprimer" link $('#supprimer').show(); // Optional: If you want to toggle show/hide on repeated clicks, replace .show() with .toggle() // $('#supprimer').toggle(); }); }); </script>
Alternative: Hide via jQuery instead of CSS
If you'd rather handle the initial hiding with jQuery (no extra CSS needed), adjust the script like this:
$(document).ready(function() { // Hide "Supprimer" on page load $('#supprimer').hide(); $('#Ajouter').on('click', function(e) { e.preventDefault(); $('#supprimer').show(); }); });
Quick Notes:
- Double-check your IDs: jQuery is case-sensitive, so
#Ajouterwon't match#ajouter - If you're using a Twig base layout, include the jQuery script in your base template so it's available across all pages instead of adding it to every individual template
内容的提问来源于stack exchange,提问作者Louay Baccary

