我创建了一个按钮,让用户可以创建新的文本输入。我正在尝试获取新创建的输入的文本输入的值。
HTML
<div class='pop-up-box-radio' Title="Edit Radios">
<div style="display: inline; float: left; margin-left: 5%;">
<div style="clear: both;">
<ul class="new-radios"></ul>
</div>
<p style="padding-top: 15px;">
<input type="button" class="add-radio" value="New Radio" />
</p>
<p>
<input type="button" class="values" value="Values" />
</p>
<p class="theValues"></p>
</div>
</div>
jQuery
// ADD RADIO
$('.add-radio').click(function(){
$("ul.new-radios").append("<li class='radioLi'><div style='dispaly: inline;'><input class='added-radio' type='text' style='width: 150px;' /><input type='button' class='deleteRadio' value='X' /></div></li>");
});
// GET VALUE OF INPUT
var newRadio = $('input.added-radio').val();
$('.values').click(function(){
$("p.theValues").append("<p>" + newRadio + "</p>");
});
// DELETE RADIO
$('div.pop-up-box-radio').on('click', 'input.deleteRadio', function() {
var clickedButton = $(this);
clickedButton.parent().remove();
});
当单击值按钮时,我得到的唯一响应是“未定义”。
最佳答案
您需要对 JS 进行轻微修改才能找到您找到的新元素。
首先,var newRadio
将在浏览器加载时运行,而不是在单击函数上运行来创建新输入。最好的选择是在单击 .values
按钮时运行它。
其次,.click()
无法找到动态创建的元素。如果将其更改为 .on('click'
函数,它将能够找到动态添加的元素。
第三也是最后一点,这只会找到一个元素,而不会找到所有元素。如果您创建一个 each()
函数并循环遍历,您将能够找到所有输入。
// ADD RADIO
$('.add-radio').click(function() {
$("ul.new-radios").append("<li class='radioLi'><div style='dispaly: inline;'><input class='added-radio' type='text' style='width: 150px;' /><input type='button' class='deleteRadio' value='X' /></div></li>");
});
$('.values').on('click', function() {
var list = ''; // create list variable
$('input.added-radio').each(function() { // start each loop
var curRadio = $(this).val(); // get value of current item
list += curRadio + ' - '; // append it to the list
}); // end loop
$("p.theValues").append("<p>" + list + "</p>"); // append list to the page
});
// DELETE RADIO
$('div.pop-up-box-radio').on('click', 'input.deleteRadio', function() {
var clickedButton = $(this);
clickedButton.parent().remove();
});
li {
list-style: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='pop-up-box-radio' Title="Edit Radios">
<div style="display: inline; float: left; margin-left: 5%;">
<div style="clear: both;">
<ul class="new-radios"></ul>
</div>
<p style="padding-top: 15px;">
<input type="button" class="add-radio" value="New Radio" />
</p>
<p>
<input type="button" class="values" value="Values" />
</p>
<p class="theValues"></p>
</div>
</div>
关于javascript - 如何获取用户创建的输入的用户文本输入的值,jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33042274/