You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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>

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 #Ajouter won'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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:20:58