繁体   English   中英

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

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

下面的链接代码基本上我正在使用 json 文件中的配方成分填充表格。 我希望能够单击单个成分并在下面的 div 上显示描述。 尝试仅针对 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>

谢谢

您遇到的问题是当您添加一个事件处理程序时,它附加到当时可用的元素。

您想要做的是使用事件委托,因此它将附加到未来的项目。

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

暂无
暂无

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

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