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

How to add an event handler to an element which is rendered on a button click?

本文关键字:按钮 元素 单击 事件处理 程序 添加      更新时间:2023-09-26

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

您有两个选择

  1. 在文档就绪中调用 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;
        };
    });
    
  2. 或在点击事件中设置 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;
           };
        });
    });