我正在尝试将图像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>
答案 0 :(得分:1)
您未定义的原因是
document.sampleForm.image.value = "images/"+img.attr('src')+"";
不是HTMLImageElement的属性。您需要.src
。
document.sampleForm.image.src = "images/"+img.attr('src')+"";
但是@Barmar说你真的不应该这样做。