[英]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> </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 : 您可以根据迭代器为<li>
标记设置一个“ id”:
for(var i=0; i<questList.length; i++){
tr.push('<li class="questList" id="quest-' + i + '">' + questList[i].questText + '</li>');
tr.push('<p> </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 : 如果您使用click
事件来选择列表中的元素,则可以使用以下函数获取其值:
$('.questList').click(function(){
var x = $(this).text();
});
In this case, no need for "id" or "data" attribute. 在这种情况下,不需要“ id”或“ data”属性。
PS : Correct me if I'm wrong but with data attribute, I think you'll have same problems to know witch id to use. PS:如果我错了,请纠正我,但具有数据属性,我想知道使用女巫的问题也一样。
Here are the things you can do : 您可以执行以下操作:
for(var i=0; i < questList.length; i++)
{
tr.push('$('<li/>',
{
class : "questList",
text : questList[i].questText
}));
tr.push('$('<p/>',
{
text : " "
}));
}
Getting the li value on selecting it. 选择时获得li值。
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. 由于您是动态创建元素的,因此可以在创建的li上委派click事件,并在文档级别上注册它,以便文档可以侦听标记。
$(document).on('click','.questOl .questList', function()
{
var selectedLiText = $(this).text();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.