[英]Get to newly created list element on submit
I need to get to newly created list elements , so I can loop through them on submit
. 我需要进入新创建的列表元素,以便在
submit
可以遍历它们。
Let's Start of with select
and empty ul
: 让我们从
select
和空ul
:
<select name="car" id="js_car_select">
<option value="1">BMW</option>
<option value="2">Audi</option>
</select>
<ul id="js_car_list"></ul>
and some basic jQuery: 和一些基本的jQuery:
// Append car name to the list on select change
$('#js_car_select').on('change', function() {
$('#js_car_list').append('<li>' + $(this).find('option:selected').text() + '</li>');
});
After this I have a list of cars as newly created elements. 之后,我将汽车列表作为新创建的元素。
How can I get to them on submit
? 我如何
submit
给他们? Now when I try, none of the new li
elements is available - $('#js_car_list li').length
= 0. 现在,当我尝试时,没有新的
li
元素可用- $('#js_car_list li').length
= 0。
How and where should I listen to new elements creation? 我应该如何以及在哪里聆听新元素的创作?
EDIT: 编辑:
The select
and ul
are part of the interface. select
和ul
是接口的一部分。 On submit
I want to append the new list to a form as hidden input
s, so they can be serialized with the whole form. 在
submit
我想将新列表作为隐藏的input
s附加到表单,以便可以将它们与整个表单序列化。
You have to replace 你必须更换
$('#js_car_list').append('<li>' + $(this).text() + '</li>');
with 同
$('#js_car_list').append('<li>' + $(this).find('option:selected').text() + '</li>');
because $(this)
refers to <select>
element. 因为
$(this)
引用<select>
元素。
So, in order to append only the selected option, you have to target the selected one with option:selected
. 因此,为了仅附加选定的选项,您必须使用
option:selected
定位选定的option:selected
。
$('#js_car_select').on('change', function() {
$('#js_car_list').append('<li>' + $(this).find('option:selected').text() + '</li>');
});
$(document).on('click', '#submit', function() {
var list = [];
$('#js_car_list > li').each(function() {
list.push($(this).text());
});
// append the list items where ever you want ..
alert(list);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.