简体   繁体   中英

Get the value of a cell in a dynamically generated table with jquery

Link code below basically I'm populating a table with recipe ingredients from a json file. I want to be able to click on a individual ingredient and display the description on a div below. Tried just targeting td elements without using a class tried wrapping them in anchor tags as well as building html on click on each cell when it was created,

                if (data['drinks'][0]['strIngredient' + i] !== null) {
                    $("#recipe").append($('<tr>'))
                    $("#recipe").append($('<td class ="ingredient"></td>').html(data['drinks'][0]['strIngredient' + i]).val(data['drinks'][0]['strIngredient' + i]));
                    $("#recipe").append($('<td></td>').html(data['drinks'][0]['strMeasure' + i]));
                    $("#recipe").append($('</tr>'));
                    i++;
                } else iCheck = true;
            }

                 $(".ingredient").click(function () {
                      console.log('fired')
                  })


<div id="drinkDescription">
    <p id="name" name="name"></p>
    <br>
    <table id="recipe" name="recipe">

    </table>
    <br>
    <p id="description" name="description">

    </p>

</div>

Thanks

The problem that you are having is when you add an event handler it attaches to the elements that are available at that point.

What you want to do is use event delegation so it will attach to future items.

$("#recipe").on("click",".ingredient",function () {

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