如何使用 jQuery select 嵌套在数据属性中的 id?

How do I select an id nested inside a data attribute using jQuery?

我有一个删除按钮,单击该按钮会触发弹出窗口。在那个弹出窗口中,我有真正的 link 进行删除。我想 select 弹出窗口的 data-content(Bootstrap) 中 link 的 ID。

我在一个页面上有多个可以删除的元素,所以我事先不知道它们的 ID 但它们具有相同的 class,所以我生成一个 ID,然后使用 $(this).attr('id') select 删除 link.

这是弹出按钮和数据内容中的 link

<button tabindex="0" role="button" class="btn btn-danger btn-sm" data-toggle="popover"           
   data-placement="top" data-html="true" data-content="<a class='btn delete-draw text-danger' 
   id='[generatedId]'>Delete Draw</a>">Delete Draw
</button>

现在这是 jquery 代码

$(".delete-draw").click(function () {
    event.preventDefault();
    var drawId = $(this).attr("id");
    // make ajax delete call
 });

如果我将 id.delete-draw class 移动到外部弹出按钮,效果很好。所以我认为这与嵌套在另一个 data-attribute

中的 a 标签的 id 有关

您可以在 $() 中传递 custom 属性,然后访问 id 值。

演示代码 :

$(".btn-sm").click(function() {
  event.preventDefault();
  //getting custom attribute
  var drawId = $(this).attr("data-content");
  //selecting id using that elemnt
  var ids =$(drawId).attr('id')
  console.log(ids)

 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button tabindex="0" role="button" class="btn btn-danger btn-sm" data-toggle="popover" data-placement="top" data-html="true" data-content="<a class='btn delete-draw text-danger' 
   id='1324'>Delete Draw</a>">Delete Draw
</button>

因为 anchor 标签标记是在 DOM Ready 事件之后添加到页面的,所以这里是 select 该标签的方式:

$(document).on('click', '.delete-draw', function() {
    let id = this.id;
    console.log( id );
});