简体   繁体   中英

How to select single element value which created dynamically in html using jQuery / Javascript?

I have a scenario like this:

for (var k in active) {
        notifications.append(
            '<a href="javascript:toast();">' +
            '<div>' +
            '<input class="phone_number" type="hidden" id='+active[k].phone_number+' value='+active[k].phone_number+'>'+
            '</input>'+
            '<span class="notify bg-blue">' + '<i class="fa fa-clock-o"></i>' + '</span>' +
            '<span>' +
            '<span>Sim ' + active[k].phone_number + ' Expires in ' + active[k].expiry_count + 'days</span>' +
            '<br/>' +
            '<span class="time">Just Now</span>' +
            '</span>' +
            '</div>' +
            '</input>'+
            '</a>');
    }

i created dynamic elements using jade template engine. here i need to identify each <a> click and i nedd to get the value of hidden field.

function toast() {
    var grade;
    //var phone_number=document.getElementById('phone_number').value;
    $.each($('.phone_number'), function () {
                    grade = $(this).val();
        alert(grade);
    });
}

by doing this i got a loop of value. which i didn't want. i need single item value. how to solve this ?

pass this to the toast

 '<a href="javascript:toast(this);">' +

and change the toast method to

function toast( thisObj ) 
{
    var grade = $( thisObj ).parent().find( '.phone_number[type="hidden"]' ).attr( "value" );
    alert( grade );
}

 notifications = $(".notifications") active = [{ phone_number: "982334",expiry_count: "1"}, { phone_number: "982334",expiry_count: "1"}] var k; for (var k in active) { notifications.append( '<a href="javascript:toast();">' + '<div>' + '<input class="phone_number" type="hidden" id='+active[k].phone_number+' value='+active[k].phone_number+'>'+ '</input>'+ '<span class="notify bg-blue">' + '<i class="fa fa-clock-o"></i>' + '</span>' + '<span>' + '<span>Sim ' + active[k].phone_number + ' Expires in ' + active[k].expiry_count + 'days</span>' + '<br/>' + '<span class="time">Just Now</span>' + '</span>' + '</div>' + '</input>'+ '</a>'); } $(document).on('click', 'a', function(){ alert($(this).find('.phone_number').val()) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="notifications"></div> 

Its simple.Try this

    $(document).on('click', 'a', function(){
          alert($(this).find('.phone_number').val())
    })

Send the toast function the k you are iterating over

'<a href="javascript:toast(' + k + ');">'

then use k in your function

function toast(k) {
   //use k (maybe select by id)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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