javascript - 如何将事件处理程序添加到单击按钮时呈现的元素?

标签 javascript jquery

我在一个页面上有两个链接。当我单击第二个链接时,它会显示某些字段。我想为其中一个字段编写一个 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/

相关文章:

javascript - 使用 jQuery 修改 CSS 类的名称 - 无法加载

javascript - 函数不接受回调

javascript - 将文件大小与单独的文件输入一起添加

Javascript 图像大小调整在 IE11 中无法正常工作,但在剩余版本(10,9,8)中工作

javascript - 单例模式javascript

php - 控制浏览器缓存

javascript - 使用标签在 url 上添加 GET 参数

jquery - 我们可以注册一个写在外部文件上的自定义 Handlebars 助手吗?

jQuery 子级 href 单击不起作用

php - 在PHP中获取cookie值?