简体   繁体   中英

how do I use a button to display <div> in django template?

results.html

{%if searched_user %}

<a href= "{{ searched_user }}">{{searched_user}}</a>

    <button id=likedsongsbutton>View liked songs</button>
<div>
{% for each_searched_user in searched_user %}
    <br id="likedsongs"/>{% for liked_songs in each_searched_user.liked_songs.all %}{{liked_songs}} 
<br/>
                            {% endfor %}

{% endfor %}
{% endif %}
{% endblock %}
</div>

<script>
    document.querySelector("#likedsongsbutton").addEventListener(onclick, )
</script>

views.py

def results(request):
if request.method == "GET":
    search_query = request.GET.get("username")
    searched_user = UserProfile.objects.filter(
            user__username__contains=search_query
        )
    return render(
    request, "results.html", {
        "searched_user":searched_user
    })

My question is how do I make the <div> show only when the button is clicked? I do not know what function to pass in the EventListener

If you give your change you div to have an id of myDiv and set the display to be None, you can pass the following lambda in as the second parameter.

() => {document.getElementById("myDiv").style.display = ""}

While the div looks like:

<div id="myDiv" style="display: none"></div>

I also think you should change it from onclick, to "click". Here is a complete example:

<button id=likedsongsbutton>View liked songs</button>
<div id="myDiv" style="display: none; background: blue; height: 100px; width: 100px;"></div>
<script>
    document.querySelector("#likedsongsbutton").addEventListener("click", () => {
        document.getElementById("myDiv").style.display = ""
    });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM