【问题标题】:jQuery - Cant get attribute of appended elementjQuery - 无法获取附加元素的属性
【发布时间】:2016-12-06 18:44:31
【问题描述】:

我正在尝试获取已附加到 HTML 中的元素的 ID 属性。但是,我得到的只是“未定义”。我该如何解决这个问题?

jQuery('form#formular').append('<input id="upload_image_button" type="button" class="button" value="Upload" onclick="myFunction();" />');

function myFunction (){
    alert(jQuery(this).attr("id"));
}

【问题讨论】:

    标签: javascript jquery append attr


    【解决方案1】:
    $('body').find('input[class="button"]').attr('id')
    

    或者尝试将id作为函数的参数传递

    ...append('<input id="upload_image_button" type="button" class="button" value="Upload" onclick="myFunction(this.id);" />');
    
    function myFunction(id){
     alert(id)
    }
    

    【讨论】:

      【解决方案2】:

      你可以在函数参数中传递'this',在函数定义中你会得到整个输入标签

      jQuery('form#formular').append('<input id="upload_image_button" type="button" class="button" value="Upload" onclick="myFunction(this)" />');
      
      function myFunction(e){
      $(e).attr('id')
      }
      

      【讨论】:

      • e 将事件,如果不使用它的属性,您将无法获取 id
      猜你喜欢
      • 2015-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多