gpt4 book ai didi

javascript - 如何以动态形式遍历每个选择元素

转载 作者:行者123 更新时间:2023-11-29 22:03:59 26 4
gpt4 key购买 nike

我看到了this用于克隆具有递增 ID 的表单字段的帖子 - 效果很好。

但是,在我的改编中,我在克隆表单中添加了一个选择框。选择框的 id 应该递增。目标是当一个特定的选择(在每个克隆字段中总是相同的)被选择时,一些隐藏的输入被揭示。

我可以使用 javascript 为一组已知的选择元素执行此操作,但我不知道如何迭代每个克隆的 select,因为用户可以根据需要创建任意数量的元素?

一个简单的版本是这样的:

HTML

<div id="zero_form" style="display:none;">
<p>
<input id='box1_' type="text" style="width:125px" placeholder='Type'>
<br>
<select id='box2_' class="first_input" style="width: 200px;" placeholder="Choose a Value">
<option value="Choose a Value">Choose a Value</option>
<option>NEGATIVE</option>
<option>EQUIVOCAL</option>
<option>POSITIVE</option>
</select>
<input id='box3_' style='display:none;' placeholder='Score #1'>
<input id='box4_' style='display:none;' placeholder='Score #2'>
<input id='box5_' style='display:none;' placeholder='%'>
<input id='box6_' type="text" placeholder="Enter Comments" style="width:200px">
<input type="button" id="remove" class="removebutton" value="Delete">
<br>
</p>
</div>
<!-- end hidden clone div-->
<form>
<p>
<span id="add" class="addbutton">Add another row</span>
</p>
</form>

jQuery

 $(document).ready(function () {
// show hidden inputs on POSITIVE selection
$('input [type=select]').each(function(){
var sel = $(this).val();
if (sel == 'POSITIVE'){
$(this).parent().find('[type=text]').show();}
else {
$(this).parent().find('[type=text]').hide();}
});

// clone fields
var form_index = 0;
$("#add").click(function () {
form_index++;
$(this).parent().before($("#zero_form").clone().attr("id", "zero_form" + form_index));
$("#zero_form" + form_index).css("display", "inline");
$("#zero_form" + form_index + " :input").each(function () {
$(this).attr("id", $(this).attr("id") + form_index);
});
$("#remove"+form_index).click(function () {
$(this).closest("div").remove();
});
});

});

JSfiddle

我对 each 函数中的语法有什么不理解的地方?请帮忙!

最佳答案

  • 您需要使用更改处理程序来监听选择元素的更改事件
  • 因为你有动态元素,你需要使用事件委托(delegate)
  • 为了使元素访问更容易,我还对 dom 进行了一些更改 - 添加了一些类属性


    选择一个值 消极的 模棱两可 积极的

    添加另一行

然后

$(document).ready(function () {
// show hidden inputs on POSITIVE selection
$(document).on('change', '.zero_form select.first_input', function () {
var sel = $(this).val();
$(this).parent().find('input.positive').toggle(sel == 'POSITIVE');
});
$(document).on('click', '.zero_form .removebutton', function () {
$(this).closest("div").remove();
});

// clone fields
var form_index = 0;
$("#add").click(function () {
form_index++;
var $from = $("#zero_form").clone().attr("id", "zero_form" + form_index).insertBefore($(this).parent())
$from.css("display", "inline");
$from.find(":input").each(function () {
$(this).attr("id", $(this).attr("id") + form_index);
});
});

});

演示:Fiddle

关于javascript - 如何以动态形式遍历每个选择元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22004355/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com