如何将事件处理程序添加到单击按钮时呈现的元素
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 获取元素。所以我不能在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();
});
您有两个选择
-
在文档就绪中调用 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; }; }); });
相关文章:
- 是否有任何可能的原因使我应该指定类型=“”;按钮“;用于我的按钮元素
- jquery点击事件不会在iPhone中的按钮元素上触发
- 如何使用jQuery从DOM中删除所有单选按钮元素
- 按钮元素没有响应
- 使用 JavaScript 获取按钮元素和样式按钮
- 获取单选按钮元素的span子项
- 如何使用 JavaScript 操作 html 按钮元素的“onclick”事件
- 使用 BeautifulSoup 解析 Javascript 按钮元素中的 HTML
- 如何使下拉列表展开单击按钮元素
- 在 JS 的单选按钮元素 (HTML) 中使用 title 属性
- 无法在无头模式下使用 watir Webdriver 执行按钮元素的 onclick 事件 javascript
- 如何从页面上的按钮元素中删除禁用
- 如何使用 JavaScript 将输入提交元素转换为按钮元素
- JQuery 按属性选择按钮元素
- 如何将对象存储到数组中,然后在create按钮元素中显示所有对象
- 正在创建带有文本的按钮元素
- 更改当前按钮元素的类
- 单击函数中的按钮元素,JavaScript
- 如何将JavaScript应用于引导程序btn组以选择/取消选择子按钮元素
- 初始化DIV中的按钮元素