简体   繁体   English

如何获取在JavaScript中动态创建的Button(onClick)的ID

[英]How to get ID of Button(onClick) which is created dynamically in javascript

How to get ID of button which is created by using following JS. 如何获取通过使用以下JS创建的按钮的ID。 I want to set Button's ID on as label's text. 我想将Button的ID设置为标签的文本。

function addnewsubj(){
var a = $("#subjname").val();

if(a!==""  ){
    $('.techsubj').append(
    '<div class="row sub'+ a +'" id="sub'+ a +'">'+
        '<div class="col-xs-6 col-md-4">'+
            '<a href="#fourth" id="'+ a +'" class="btn btn-info" >'+ a +'</a>'+
        '</div>'+
        '<div class="col-xs-12 col-sm-6 col-md-8">'+
            '<div class="progress">'+
                '<div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%">'+
                    '<span class="sr-only">60% Complete (warning)</span>'+
                '</div>'+
            '</div>'+
        '</div>'+
    '</div>'
    );
}
else{
    alert("Text Box is empty");
}}

HTML HTML

<label id="subjTitle">  </label>

You don't have a button anywhere. 您在任何地方都没有按钮。 If you mean the anchor element that is styled as a button, 如果您指的是样式为按钮的锚元素,

$('subjTitle').text($('.techsubj .btn').attr('id'))

Or, you could always explicitly create it with an ID, or best of all you could create the content as a DOM hierarchy instead of as a HTML source and just keep the reference to the "button" object around. 或者,您始终可以使用ID显式地创建它,或者最重要的是,您可以将内容创建为DOM层次结构而不是HTML源,而只需保留对“ button”对象的引用即可。

use jquery 'on' method for dynamic event. 对动态事件使用jquery'on'方法。 use this code: 使用此代码:

$(document).on('click','.btn-info', function(){
  $('#subjTitle').text($(this).attr('id'));
});

if you are using jquery below version 1.7 than you may use "live" or "delegate" for dynamic element. 如果您使用的jQuery版本低于1.7,则可以对动态元素使用“实时”或“委托”。

Here is a little Example: 这是一个小例子:

HTML : HTML:

  <div id='th'></div>

Jquery: jQuery的:

  $('#th').append('<div id="rock">this is Dynamo</div>');

  alert($($('#th').children('div')[0]).attr('id'));

may it helps you! 希望对您有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM