首页 > 解决方案 > Tippyjs - 如何将单击按钮上的数据值传递给模板

问题描述

我有多个按钮使用创建动态模板的相同tippy 函数。我需要从单击的按钮中获取 data-value="" 并将其传递给tippyjs。

按钮

<div class="d-none d-lg-flex show-context-menu" data-value="song450">

提示 js

 tippy(".show-context-menu", {
 
  
  trigger: "click",
  placement: "bottom-start",
  allowHTML: true,
  interactive: true,
  hideOnClick: true,
  inertia: true,
  onShow(instance) {
    
    if ($("#parent-row-" + $(this).data("value")).length) {
      $("body").addClass("no-scroll");
      var e = $.parseJSON($("#parent-row-" + $(this).data("value")).html());
      console.log("#parent-row-" + $(this).data("value"));
    } else e = CurrentSongInfo,
   
    instance.setContent(` Dynamic template is here`);
  },
});

现在我有 $(this) 用于获取按钮。我尝试了多种方法,但没有任何方法可以传递数据 ID

标签: javascripttippyjs

解决方案


试试这样,希望对你有帮助。

$(".show-context-menu").each(function() {
  tippy($(this)[0], {
    content: $(this).attr("data-value"),
    trigger: "click",
    placement: "bottom-start",
    allowHTML: true,
    interactive: true,
    hideOnClick: true,
    inertia: true,
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://unpkg.com/@popperjs/core@2"></script>
<script src="https://unpkg.com/tippy.js@6"></script>

<div class="show-context-menu" data-value="song450">Button 1</div>
<div class="show-context-menu" data-value="song550">Button 2</div>
<div class="show-context-menu" data-value="song650">Button 3</div>


推荐阅读