[英]How to add an event handler to an element which is rendered on a button click?
我在頁面上有兩個鏈接。 當我單擊第二個鏈接時,它顯示某些字段。 我想為其中一個字段編寫一個onkeyup()
事件處理程序。 我已經編寫了這樣的代碼,但我缺少了一些東西。 請幫忙。
var inputBox;
$().ready(function() {
//cc_sec is the id of the second link in my page.
$('#cc_sec').click(function(){
inputBox = document.getElementById("{!$Component.pg.pb.cardForm.cardnumber}");
alert(inputBox.id);
//This alert is giving me the ID of the element correctly.
});
//This is not working. inputBox is declared as global variable.
inputBox.onkeyup = function(){
alert(inputBox.value);
document.getElementById('printCardNo').innerHTML = inputBox.value;
}
});
請指出我的錯誤。 TIA :)
更新:只有單擊cc_sec
鏈接后,我才能通過ID獲取元素。 所以我不能做inputBox = document.getElementById("{!$Component.pg.pb.cardForm.cardnumber}");
在ready
功能的開始。
使用jQuery .on
將eventhandler添加到動態創建的元素中。
$('body').on("keyup","{!$Component.pg.pb.cardForm.cardnumber}",function(){
alert($(this).val());
document.getElementById('printCardNo').innerHTML = $(this).val();
});
你有兩個選擇
在准備好文檔中調用document.getElementById:
var inputBox; $().ready(function() { inputBox = document.getElementById("{!$Component.pg.pb.cardForm.cardnumber}"); //cc_sec is the id of the second link in my page. $('#cc_sec').click(function() { alert(inputBox.id); //This alert is giving me the ID of the element correctly. }); inputBox.onkeyup = function() { alert(inputBox.value); document.getElementById('printCardNo').innerHTML = inputBox.value; }; });
或在點擊事件中設置onkeyup:
var inputBox; $().ready(function() { //cc_sec is the id of the second link in my page. $('#cc_sec').click(function() { inputBox = document.getElementById("{!$Component.pg.pb.cardForm.cardnumber}"); alert(inputBox.id); //This alert is giving me the ID of the element correctly. inputBox.onkeyup = function() { alert(inputBox.value); document.getElementById('printCardNo').innerHTML = inputBox.value; }; }); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.