作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想使用-6ren">
我有下一个用于上传图像的 PHP/HTML 代码:
<label>Image (*)</label>
<!-- if image exists, show it -->
<?php if($category->getImage() === null) : ?>
<input type="file" name="image" id="image" required>
<?php else : ?>
<p><img src="../uploads/images/<?php echo $categoria->getImage(); ?>"></p>
<input type="file" name="image" id="image">
<?php endif; ?>
我想使用 JavaScript 验证它
// Validate image
image = document.getElementById("image").value;
if (!image) {
window.alert("You must select a file for the image.");
document.getElementById("image").focus();
return false;
}
图片为必填项。如果您创建一个新的注册表,它会将其所有属性设置为空,包括图像。然后,图像不会显示,您可以在表单中设置它。如果您想更新它们,表单会显示当前图像,但如果您不想,则不必更新。
我需要验证文件是否尚未上传并且值为空,这意味着用户正在创建新的注册表并且需要图像。如果文件尚未上传,但其值不为空,则用户正在更新注册表,不需要上传图片。
提前致谢,并对我的英语不好表示歉意。
最佳答案
可以给图片添加id
<img id="foo" src="../uploads/images/<?php echo $categoria->getImage(); ?>">
并检查它是否在 DOM 中:
if ($('#foo').length) {
// image is there
}
或者不使用 jQuery:
if (document.getElementById("foo")) {
// image is there
}
关于javascript - 如何在 JavaScript 中管理 PHP 代码中的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35273853/
我是一名优秀的程序员,十分优秀!