![](/img/trans.png)
[英]How change the styling of dynamically generated JSX via a button click in React Native
[英]How to react on the dynamically generated button click?
我用以下代碼添加按鈕:
$('.dishes').prepend($('<div class="row" data-dishid="'+dishid+'"><div class="col-md-8">'+dishname+'<button type="button" class="close" aria-label="Close"><span aria-hidden="true">×</span></button></div></div>'));
但是以下代碼無法捕獲按鈕單擊(如果它是靜態html的一部分,則可以使用相同的代碼):
$("button.close").click(function() {
var row = $(this).closest('.row');
var dishid = row.attr('data-dishid');
});
我該如何解決?
請參閱示例代碼 。
對於動態創建的元素,應使用.on('click', selector, callback)
喜歡
$(document).on("click", "button.close", function() {
var row = $(this).closest('.row');
var dishid = row.attr('data-dishid');
});
我已經看到了代碼。 您必須在附加元素之后立即調用動態元素的click函數。 試試下面的代碼。
$("#add").on('click', function() {
$('.dishes').prepend($('<div class="row" data-dishid="'+ "test" +'"><div class="col-md-8">'+ " test " +'<button type="button" class="close" aria-label="Close"><span aria-hidden="true">×</span></button></div></div>'));
$("button.close").on('click', function() {
var row = $(this).closest('.row');
var dishid = row.attr('data-dishid');
console.log(dishid);
});
});
$("button.close").on("click", function(){
console.log('ok');
});
您需要將on()函數用於動態生成的html元素
嘗試:
$("button.close").on("click", function() {
console.log('ok');
});
您需要.on事件處理程序來動態創建DOM元素。
更新:
您無需將jQuery $
放在前綴的內容之前。 這是與您的代碼一起工作的小提琴。
這是您更新的代碼 。
我變了:
$("button.close").click(function() {
var row = $(this).closest('.row');
var dishid = row.attr('data-dishid');
});
至:
$(".dishes").on('click', 'button.close', function() {
var row = $(this).closest('.row');
var dishid = row.attr('data-dishid');
console.log(dishid);
});
這個問題在互聯網上得到了解答,這是jQuery網站的摘錄:
事件處理程序僅綁定到當前選定的元素; 它們必須在您的代碼調用.on()時存在。 或者,使用委托事件來附加事件處理程序。
委派事件的優勢在於,它們可以處理來自后代元素的事件,這些事件在以后的時間添加到文檔中。
在檢查您的代碼后,單擊事件應該可以正常工作。 也許問題取決於時機 。 我的假設是,如果您有以下代碼:
$("button.close").click(function() {
var row = $(this).closest('.row');
var dishid = row.attr('data-dishid');
});
您尚未將對象附加到DOM上。 每次調用下面的方法時,都必須立即綁定click事件。 最好是將代碼放在一起,以檢查其是否有效。
$('.dishes').prepend($('<div class="row" data-dishid="'+dishid+'"><div class="col-md-8">'+dishname+'<button type="button" class="close" aria-label="Close"><span aria-hidden="true">×</span></button></div></div>'));
$("button.close").click(function() {
var row = $(this).closest('.row');
var dishid = row.attr('data-dishid');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.