簡體   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