我在一个页面上有两个链接。当我单击第二个链接时,它会显示某些字段。我想为其中一个字段编写一个 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获取元素。所以我不能在 ready
函数的开头执行 inputBox = document.getElementById("{!$Component.pg.pb.cardForm.cardnumber}");
。
最佳答案
使用 jQuery .on
将事件处理程序添加到动态创建的元素。
$('body').on("keyup","{!$Component.pg.pb.cardForm.cardnumber}",function(){
alert($(this).val());
document.getElementById('printCardNo').innerHTML = $(this).val();
});
关于javascript - 如何将事件处理程序添加到单击按钮时呈现的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36150657/