我试图在按下按钮时应用一个函数,但有时会附加该按钮,所以我尝试将该函数应用于他的类。问题是只有当我将它链接到按钮 ID 时我才能使该功能工作,当我链接类时什么也没有发生。这会发生在附加的按钮和普通按钮上。
$(document).on('click', '.createCustomLayer', function () {
alert("Alert");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-light form-control" id="createCustomLayer" class="createCustomLayer" style="margin-top: 32px;">Create a custom layer</button>
如果我将 .createCustomLayer
更改为 #createCustomLayer
,一切正常。
最佳答案
你不能让多个 class=""
将 createCustomLayer
移动到 class="btn btn-light form-control"
中,所以它看起来像 class="btn btn-light form-control createCustomLayer"
演示
$(document).on('click', '.createCustomLayer', function () {
alert("Alert");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-light form-control createCustomLayer" id="createCustomLayer" style="margin-top: 32px;">Create a custom layer</button>
关于javascript - 为什么我可以将 JS/Jquery 函数应用于按钮特定 ID,但不能链接到他的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55220869/