【问题标题】:Attach attribute [data-name] then click using this data attribute [duplicate]附加属性 [数据名称] 然后单击使用此数据属性 [重复]
【发布时间】:2019-04-30 11:50:17
【问题描述】:
我试图在单击一个元素时添加一个 data-name 属性,然后在单击该元素时执行其他操作。
$(".btn01").on("click", function() {
$(".next").attr("data-name", "btn02");
});
$("[data-name='btn02']").on("click", function() {
console.log("I clicked this button");
});
它在 DOM 中更新但不工作?
有什么想法吗?
【问题讨论】:
标签:
javascript
jquery
html
attr
【解决方案1】:
您必须使用事件委托,因为您在第二次点击事件 [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】:
尝试以下操作,使用事件委托将事件附加到“[data-name='btn02']”,因为 $("[data-name='btn02']") 元素直到 $(". btn01") 被点击。
$(".btn01").on("click", function() {
$(".next").attr("data-name", "btn02");
});
$(document).on("click", "[data-name='btn02']", function() {
console.log("I clicked this button");
});
【解决方案3】:
如果您只是想做到这一点,因此需要在第二个按钮之前单击第一个按钮,您可以为此使用 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");
}
});