提问者:小点点

如何将父数据属性值应用于动态插入的按钮


我有一些像这样的标记:

<table id="fcm_table">
    <tbody>
        <tr>
            <td class="hs_button" data-buttonID="<?php echo $buttonID; ?>"></td>
        </tr>
        //multiple instances of the <tr><td> in the table
    </tbody>
</table>

我需要在中插入一个锚标记,并应用“按钮ID”作为href,但是我不能以父TD的data-buttonid值为目标。我一直没定义。

function hs_button_dyn() {
   var button_ID = $(this).parent('td.hs_button').data('buttonID');
   var content = '<a id="bar" href="' + button_ID + '">foo</a>';
   $('#fcm_table tbody tr td.hs_button').prepend(content);
}

$(function(){
    hs_button_dyn();
});

共1个答案

匿名用户

试试这个。

$(function(){
  function hs_button_dyn(el) {
    $("<button>", {
      id: "bar"
      href: $(el).data("buttonID")
    }).html("foo").prependTo(el);
  }
  hs_button_dyn('#fcm_table tbody tr td.hs_button');
});

在您的代码中,this将引用函数,而不是页面中的元素。所以这对你没有用。

您可以传入一个元素,然后执行所需的更新。

更新

如果您有多个TD,可以循环它:

$(function(){
  function hs_button_dyn(el) {
    $("<button>", {
      id: "bar"
      href: $(el).data("buttonID")
    }).html("foo").prependTo(el);
  }
  $('#fcm_table tbody tr td.hs_button').each(function(i, elem){
    hs_button_dyn(elem);
  });
});