【问题标题】:Get the value of a cell in a dynamically generated table with jquery使用jquery获取动态生成的表中单元格的值
【发布时间】:2020-12-01 21:58:36
【问题描述】:

下面的链接代码基本上我正在使用 json 文件中的配方成分填充表格。我希望能够单击单个成分并在下面的 div 上显示描述。尝试仅针对 td 元素而不使用类尝试将它们包装在锚标记中,并在创建每个单元格时构建 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>

谢谢

【问题讨论】:

  • 我们也能看到 HTML 代码吗?也许你可以创建一个 sn-p?到目前为止,您尝试过什么?
  • 有什么问题?点击事件未触发或正在触发,但不确定如何从单元格获取数据?

标签: javascript html jquery


【解决方案1】:

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

您要做的是使用事件委托,以便将其附加到未来的项目。

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

【讨论】:

  • 谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-09
  • 2014-03-15
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
  • 2013-05-16
相关资源
最近更新 更多