2

I have a script that appends a piece of HTML 10 times

$('#main').append(`
<div id="box${i}" class="divMusica">

    <div class="todas">

    <img  id= "img${i}" src="">

    </div>

    <div class="divTexto">

        <h2>Nome da banda: <p id="banda${i}"></p></h2>

        <h2>Nome da música: <p id="musica${i}"></p></h2>

        <a class="referencia" id ="url${i}" href="" target="_blank" class="button">Ir para last.fm </a>

        <button button type="button" class="add-music-button" data-ref="${i}" onclick="add_to_storage()">Adicionar</button>

    </div>

</div>`);

And I'm trying to get data-ref to the sessionStorage with this code let musicRef = $(this).data("ref"); but it returns undefined. Can someone tell me why? I already tried to put ${i} without quotes too.

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
MrGredy
  • 21
  • 5
  • 3
    Please post a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example), preferably as a [stack snippet](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do). – costaparas Jan 30 '21 at 04:24

2 Answers2

1

The problem is you are missing pass this context

onclick="add_to_storage()" ---> onclick="add_to_storage(this)"

function add_to_storage(event){
  var value = $(event).data('ref');
  console.log(value);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="add-music-button" data-ref="123" onclick="add_to_storage(this)">Adicionar</button>

More detailed explanation

Because the value of this is not set by the call, this will default to the global object, which is window in a browser.

Read this post to know more about this keyword in Javascript.

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
1

You are trying to add HTML with Javascript function append() before this element has been registered by the DOM

You can't apply normal onclick event for this. You have to do Event Delegation. Then you will be able to catch the id or class of that.

This event handler is bound to an element higher up the DOM tree (in this case, the document) and will be executed when an event reaches that element having originated on an element matching the selector.

See this answer to know the difference. Link

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="main"></div>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
        let i = 1;
        $('#main').append(`
            <div id="box${i}" class="divMusica">
                <div class="todas">
                <img  id= "img${i}" src="">
                </div>
                <div class="divTexto">
                    <h2>Nome da banda: <p id="banda${i}"></p></h2>
                    <h2>Nome da música: <p id="musica${i}"></p></h2>
                    <a class="referencia" id ="url${i}" href="" target="_blank" class="button">Ir para last.fm </a>
                    <button button type="button" class="add-music-button" data-ref="${i}" id="clickButtonID${i}">Adicionar</button>
            </div>
        </div>`);

        $(document).on('click', '#clickButtonID' + i, function(){
            alert($(this).data("ref"));
        })
    </script>
</body>
</html>
wahwahwah
  • 3,254
  • 1
  • 21
  • 40
Mr. Perfectionist
  • 2,605
  • 2
  • 24
  • 35