0

我正在使用一个大型动态创建的表。它是 2+ 列,第一列是文本,第二列是文本输入字段中的值。当页面加载时,输入框有一个默认值。当我在文本字段中进行更改时,我希望能够保存该值。

当我使用 时$("#ID_NAME").val(),我会得到用户输入的任何值。如果我通过其他方式深入到输入字段,.val()则在页面加载时给我默认值。该页面实际上并没有使用任何 id,我只是添加了一个用于调试。

我发布了一个显示问题的jsfiddle。http://jsfiddle.net/GdjKp/1/

HTML:

<fieldset>
<legend>test</legend>
<table id="menuSection">
    <thead>
        <tr>
            <th>Id</th>
            <th>field</th>
        </tr>
    </thead>
    <tbody>
        <tr id="row_1">
            <td>description</td>
            <td>
                <input id="test_id" type="text" value="default value"></input>
            </td>
        </tr>
    </tbody>
</table>
</fieldset>Chane text value and click
<input type="button" value="Go" onclick="run();"> the two elements found by jQuery will be in console.log() and the two values will pop up.

JS:

function run() {
    var a = $("fieldset");
    var b = $(a[0]).find("table > tbody > tr");
    var c = $(b[0]).children();
    var d = $(c[1].innerHTML);
    var result_1 = $(c[1].innerHTML);

    var result_2 = $("#test_id");
    console.log(result_1);
    console.log(result_2);

    alert(result_1.val());
    alert(result_2.val());
}

这里发生了什么?

[编辑]
这是最终的工作代码

function save() {
    var cols = $("fieldset:first > table > thead > tr > th");
    var sections = $("fieldset");
    var ret = {};
    var sectionsTmp = {};
    var translation = {};

    for (var j=1; j < cols.length-1; j++) { //loop on language columns, skipping field names and delete columns (first and last columns)
        var lang = cols[j].innerHTML;
        sectionsTmp = {};

        for (var i=0; i < sections.length; i++) { //loop on sections/fieldsets
            var sectionName = $(sections[i]).children("legend")[0].innerHTML;
            var translations = $(sections[i]).find("table > tbody > tr");
            translation = {};

            for (var k=0; k < translations.length; k++) { //loop on translations in a section
                var translationId = translations[k].innerText.trim();
                var translationText = $(translations[k]).children().eq(j).find('input').val();
                translation[translationId] = translationText.replace(/'/g,'&apos;');
            }
            sectionsTmp[sectionName] = translation;
        }
        ret[lang] = sectionsTmp;
    }
    var url = '<?= $basePath?>/admin/save/item/translations/';
    var form = $('<form accept-charset="UTF-8" action="' + url + '" method="post">' +
        '<input type="text" name="translations" value=\'' + JSON.stringify(ret) + '\' />' +
        '</form>');
    $('body').append(form);
    console.log(form);
    form.submit();
}
4

1 回答 1

3

在 result_1 的情况下,您实际上并没有选择元素 - 您是根据其 html 克隆它。

这一行:

var result_1 = $(c[1].innerHTML);

相当于:

var result_1 = $('<input id="test_id" type="text" value="default value"></input>');

如您所见,结果 1 与输入字段中输入的内容无关 - 它与 DOM 完全分离。

于 2013-07-24T18:59:58.647 回答