循环遍历表单并从对象填充

Looping through a form and populating from an object

本文关键字:对象 填充 遍历 表单 循环      更新时间:2023-09-26

我有一个表单和一个javascript对象。

<form id="myForm">
    <input type="text" name="title">
    <input type="text" name="image">
</form>
var myObject = {title: 'this is the title', image: 'image.jpg'}

是否有一种方法可以遍历表单输入,并且如果任何输入名称与对象中的键匹配,则设置值?

请注意,我希望通过表单而不是对象运行,因为对象中有许多与表单不相关的其他数据(未在示例中显示)。

你可以这样做:

$("#myForm input:text[name]").each(function() {
    var name = $(this).attr("name");
    for (var key in myObject) {
        if (key == name) {
            $(this).val(myObject[key])
            break;
        }
    }
});

这样你就不用循环对象了,但是你必须为每个属性写一个if子句:

var myObject = {title: 'this is the title', image: 'image.jpg'}
$('#myForm input').each(function()
{
    if($(this).attr('name') === 'title')
    {
        $(this).val(myObject.title);   
    }
});