将 img src 保存到 javascript 变量


Save Img Src to Javascript Variable

我正在尝试将图像 src 设置在从我的表单传递的隐藏变量中。当我输出时,变量是"未定义的"。我对Javascript很陌生,不确定问题可能是什么。我的错误在线:

document.sampleForm.image.value = "images/"+img.attr('src')+"";

Javascript:

$('tr', '#target').each(function () {
    var tr = $(this);
    html += '<center><tr>';
    $('td', tr).each(function () {
        var td = $(this);
        if (!td.is('td.header')) {
            var img = $('img', td);
            var text = $('textarea', td).val();
            html += '<td style="width: 33%;">';
            html += (img.length) ? '<img src="' + img.attr('src') + '" style="display: block; max-width: 100%;" />' : '<div style="width: 100%;"></div>';
            document.sampleForm.image.value = "images/"+img.attr('src')+""; 
            document.forms["sampleForm"].submit();
            html += '</td>';
        } 
    });
    html += '</tr></center>';
});

.HTML:

<table id="target">
<form id="sampleForm" name="sampleForm" action="test.php" method="post">
    <tr><center>
        <td class="logo" colspan="3">
            <h3>Choose Header</h3>
          <div class="img-container"><input type="hidden" name="image" id="image" value=""></div>
        </td>
    </center>
    </tr>
    <tr>
    <td style="height:auto;">
    <?php
    $test = mysql_query("SELECT id, title FROM tmpl2");

    echo "<select class='image_select' id='logo_option' name='logo_option[]' multiple='multiple'>";

        while ($row = mysql_fetch_assoc($test))
    {
        echo "<option value='".$row[id]."'>$row[title]</option>";
    }   

    echo "</select>";

    ?>

    </td>
    </tr>

           <tr><center>
        <td class="logo" colspan="3">
                <h3>Choose Logo</h3>
          <div class="img-container"></div>
        </td>
    </center>
    </tr>
    <tr>
    <td style="height:auto;">
    <?php
    $test = mysql_query("SELECT id, title FROM tmpl2");
    echo "<select class='image_select' id='header_option' name='header_option[]' multiple='multiple'>";

        while ($row = mysql_fetch_assoc($test))
    {
        echo "<option value='".$row[id]."'>$row[title]</option>";
    }   

    echo "</select>";
    ?>
    </td>
    </tr>
</table>

你变得未定义的原因是因为

document.sampleForm.image.value = "images/"+img.attr('src')+"";

不是 HTMLImageElement 的属性。你需要.src.

document.sampleForm.image.src = "images/"+img.attr('src')+"";

但正如@Barmar所说,你真的不应该这样做。