這是我的情況:
<button id="btnSendInvoice">Button A</button>
// Btn Send Invoice
$('#btnSendInvoice').click(function() {
console.log(BUTTON A)
$("#btnSendInvoice").text("Button B")
$("#btnSendInvoice").attr("id","btnSetPayment")
});
// Btn Set Payment
$('#btnSetPayment').click(function() {
console.log(BUTTON B)
});
光學它的作業原理。如果我按下按鈕 A,我會進入控制臺“按鈕 A”,按鈕文本更改為按鈕 B,ID 也更改為 btnSetPayment。
如果我現在按下“新”按鈕 B,我會再次在控制臺中得到按鈕 A。我的錯誤在哪里?
uj5u.com熱心網友回復:
- 您撰寫的代碼不起作用的原因是,當代碼執行
$('#btnSendInvoice').click(function() {行時,它會找到帶有idas 的元素btnSendInvoice并將事件及其分配function給該元素。一開始你有按鈕withidbtnSendInvoice`,所以它會分配那個功能給它。 - 在下一行它執行
$('#btnSetPayment').click(function() {,所以它會找到帶有idas 的元素,btnSetPayment但那時不會有任何這樣的元素,所以這個事件不會分配給任何元素。 - 稍后當你點擊
Button A你改變它id但事件與element自身系結所以事件不會改變并且它將繼續觸發相同的舊功能。
解決方案1
- 更新現有
$('#btnSendInvoice').click(function() {函式并使用if ($(this).attr("id") == "btnSendInvoice") {& 等條件添加條件代碼if ($(this).attr("id") == "btnSetPayment") {。完整代碼如下。
// Btn Send Invoice
$('#btnSendInvoice').click(function() {
if ($(this).attr("id") == "btnSendInvoice") {
console.log("BUTTON A")
$("#btnSendInvoice").text("Button B")
$("#btnSendInvoice").attr("id", "btnSetPayment")
} else if ($(this).attr("id") == "btnSetPayment") {
console.log("BUTTON B")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<button id="btnSendInvoice">Button A</button>
解決方案2
- 您可以使用
delegate系結使用$(document).on("click", "#btnSendInvoice". 使用這種將事件系結document并點擊它會試圖找到delegate event利用id當前元素或任何其他有效的selectors。所以它會起作用。嘗試如下。
PS Delegate事件可能會影響性能。
$(document).on("click", "#btnSendInvoice", function() {
console.log("BUTTON A")
$("#btnSendInvoice").text("Button B")
$("#btnSendInvoice").attr("id", "btnSetPayment")
});
// Btn Set Payment
$(document).on("click", "#btnSetPayment", function() {
console.log("BUTTON B")
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<button id="btnSendInvoice">Button A</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/341460.html
標籤:查询
上一篇:日期轉換導致時區問題
