简体   繁体   English

JQuery 通过每个循环为输入文本赋值

[英]JQuery assigning a value to an input text via each loop

I have an each loop like so:我有一个像这样的每个循环:

$.each(this, function (k, v) {

                        table += '<td><input type="text" name="' + k + '" id="' + k + '" /></td>';
                        $('#' + k).val(v);
                    });

What I am trying to do is populate the input type with what is in v, if I do:我想要做的是用 v 中的内容填充输入类型,如果我这样做:

table += '<td><input type="text" name="' + k + '" id="' + k + '" value="' + v + '" /></td>';

the value gets populated with the correct value, but when I submit my form, they are being submitted as empty strings:该值填充了正确的值,但是当我提交表单时,它们被作为空字符串提交:

<script type="text/javascript">
    $("#form").submit(function (event) {
        $.post("/api/update/", $("#form").serialize(), alert('success'));
    });
</script>

I dont know why $('#' + k).val(v);我不知道为什么$('#' + k).val(v); after the input is created is not working :(创建输入后不起作用:(

Either add "/api/update/" as the "action" attribute for your form and get rid of your serialization logic, or (more likely what you were going for) put an添加“/api/update/”作为表单的“action”属性并去掉序列化逻辑,或者(更有可能是你想要的)放一个

event.preventDefault() 

at the top of your submit handler.在提交处理程序的顶部。

The issue is that your submit method by default submits the form, sending a request the form's "action" attribute, (in your case, likely the current page).问题是您的 submit 方法默认提交表单,发送表单的“action”属性请求(在您的情况下,可能是当前页面)。 Thus, your browser creates an errant submit just before executing your $.post.因此,您的浏览器会在执行 $.post 之前创建错误提交。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM