简体   繁体   中英

Get the selected list value from dynamically created order list using jQuery

I have a created dynamic order list with class name as follows

    $orderList = $('.questOl');

    for(var i=0; i<questList.length; i++){
        tr.push('<li class="questList">' + questList[i].questText + '</li>');
        tr.push('<p>&nbsp</p>')                     
    }
    $orderList.append($(tr.join('')));

Then I want to get the list value when I selecting it. I have tried several code snippet in this website. It give undefined value. The closest attempt using this line of code.

var x = $('.questOl').find('.questList').text();

But it take all the value from the list. What I want is current selected value only. Any idea?

You could set an "id" to the <li> tags based on the iterator :

for(var i=0; i<questList.length; i++){
    tr.push('<li class="questList" id="quest-' + i + '">' + questList[i].questText + '</li>');
    tr.push('<p>&nbsp</p>')                     
}

And then access it like :

var x = $('#quest-1').text();

Hope it helps.

EDIT

If you're using the click event to select the element of the list, you could get its value with a function like this :

$('.questList').click(function(){
    var x = $(this).text();
});

In this case, no need for "id" or "data" attribute.

PS : Correct me if I'm wrong but with data attribute, I think you'll have same problems to know witch id to use.

Here are the things you can do :

  1. Create li using dynamic element creating rather writing html. ( optional )

for(var i=0; i < questList.length; i++)
{
  tr.push('$('<li/>',
    { 
      class : "questList",
      text : questList[i].questText 
    }));
    tr.push('$('<p/>',  
    { 
      text : " " 
    }));
}
  1. Getting the li value on selecting it.

    Since you are creating the elements dynamically, you can delegate a click event on the li you created and register it on the document level so that the document could listen to the markup.

$(document).on('click','.questOl .questList', function()
{
    var selectedLiText = $(this).text();
});

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