gpt4 book ai didi

javascript - 为什么这个select在触发JS时会额外添加一个空选项?

转载 作者:行者123 更新时间:2023-11-28 19:36:30 26 4
gpt4 key购买 nike

我有一个非常简单的表单,里面有一些 jQuery 的东西。我想要做的是,如果我在选择字段中选择特定选项,则显示文本输入。在该输入中,我希望能够向我的选择字段添加新选项。除非我尝试多次使用它,否则它工作得很好。第一次是没问题的。第二次它为我添加了带有空值和标签的附加选项字段。第三次它添加两个空选项字段。等等...

我正在试图弄清楚为什么会发生这种事。以下是代码预览和演示: http://jsfiddle.net/rx5orekb/HTML:

<form action="#" class="source">
<select id="source">
<option value="none">None</option>
<option value="source-xyz">Source XYZ</option>
<option value="something-else">Something Else</option>
<option value="add-new">Add New Source</option>
</select>
<input type="text" placeholder="Type name and hit enter" value="" style="display: none" />
</form>

JS:

var Form = {
addNewSource: function(form, select, newSource) {
select.hide();
newSource.show().focus();

form.on('submit', function(event) {
event.preventDefault();
var label = newSource.val(),
html = '<option value="'+label+'">'+label+'</option>';

select.show().find('option[value=add-new]').before(html);
select.val(label);
newSource.hide().val('');
});
return false;
},

sourceAppendix: function() {
var select = $('.source').find('select');

select.on('change', function() {
var v = $(this).val(),
form = $(this).parents('.source'),
newSource = form.find('input');

if(v == 'add-new') {
Form.addNewSource(form, $(this), newSource);
}
});
}
}

$(document).ready(function() {
Form.sourceAppendix();
});

非常感谢!

最佳答案

每次调用 addNewSource() 时,都会绑定(bind)另一个 submit 处理程序。因此,如果您调用 addNewSource 4 次,单击提交按钮将运行提交处理程序 4 次。其中每一个都会向选择添加另一个选项。

我不太确定在将新选项添加​​到菜单之前等待提交事件要实现什么目的,所以我不确定如何更正代码。您可能只想立即添加新选项:

addNewSource: function(form, select, newSource) {
select.hide();
newSource.show().focus();
var label = newSource.val(),
html = '<option value="'+label+'">'+label+'</option>';
select.find('option[value=add-new]').before(html);
},

.submit() 处理程序应绑定(bind)在顶层,而不是在 addNewSource 内。

关于javascript - 为什么这个select在触发JS时会额外添加一个空选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25789723/

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