代码之家  ›  专栏  ›  技术社区  ›  alib0ng0

附加属性[数据名称],然后单击使用此数据属性[重复]

  •  4
  • alib0ng0  · 技术社区  · 6 年前

    这个问题已经有了答案:

    我尝试在单击一个元素时添加数据名称属性,然后在单击该元素时执行其他操作。

    $(".btn01").on("click", function() {
        $(".next").attr("data-name", "btn02");
    });
    
    $("[data-name='btn02']").on("click", function() {
        console.log("I clicked this button");
    });
    

    它正在DOM中更新,但不起作用? 有什么想法吗?

    3 回复  |  直到 6 年前
        1
  •  2
  •   Zakaria Acharki    6 年前

    必须使用事件委托,因为在第二个单击事件的选择器中使用的属性 [data-name='btn02'] 由JS代码动态创建:

    $(".btn01").on("click", function() {
      $(".next").attr("data-name", "btn02");
    });
    
    $("body").on("click", "[data-name='btn02']", function() {
      console.log("I clicked this button");
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button type="button" class="btn01">CLICK ME then click the span bellow</button>
    <br><br>
    <span class="next">Next span</span>
        2
  •  1
  •   Rohit Garg    6 年前

    尝试以下操作,使用事件委派将事件附加到“[数据名称='btn02']”,因为在单击$(“.btn01”)之前,$([数据名称='btn02'])元素将不存在。

    $(".btn01").on("click", function() {
      $(".next").attr("data-name", "btn02");
    });
    
    $(document).on("click", "[data-name='btn02']", function() {
      console.log("I clicked this button");
    });
    
        3
  •  -1
  •   hackerman58888    6 年前

    如果你只是想让第一个按钮需要在第二个按钮之前被点击,你可以使用 boolean 变量:

    var firstButtonClicked = false;
    $(".btn01").on("click", function() {
        firstButtonClicked = true;    
    });
    // the second button
    $(".next").on("click", function() {
        if (firstButtonClicked == true) {
            console.log("I clicked this button after the first one");
        }
    });