简体   繁体   English

使用 jquery 获取动态生成表中单元格的值

[英]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.下面的链接代码基本上我正在使用 json 文件中的配方成分填充表格。 I want to be able to click on a individual ingredient and display the description on a div below.我希望能够单击单个成分并在下面的 div 上显示描述。 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,尝试仅针对 td 元素而不使用 class 尝试将它们包装在锚标签中,并在创建每个单元格时在单击每个单元格时构建 html,

                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 () {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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