假设我需要选择图像从选择控件在屏幕上显示它,如果没有想要的图像我想从磁盘中选择它并将此选项放入选择控件并自动选择它。问题场景是,如果我选择“添加”选项并取消文件对话框,则“添加”选项将保持选中状态,因此如果我再次选择该选项,则不会显示文件对话框。在这种情况下,我想自动选择我隐藏的占位符选项,但我不知道如何检测没有选择任何文件。是否有一种方法可以检测并处理它?</ p>
我附加了我的html控件以及我如何使用他们的活动。
$("#file_upload").change(function() {
const file = $("#file_upload")[0].files[0];
var text = file.name.slice(0, -4);
fill_img_options(text);
});
var fill_img_options = function(text) {
$("#img_selector").append(`<option value='${text}'>${text}</option>`);
$("#img_selector").val(text).change();
};
$("#img_selector").change(function () {
const selectedName = $(this).find("option:selected").attr("name");
if (selectedName === "add") {
$("#file_upload").click();
return;
}
});
<div class="form-inline">
@*hidden element for uploading image*@
<input type="file" id="file_upload" accept=".jpg" style="position: fixed; top: -100em">
<label for="img_selector">Choose img:</label>
<select class="form-control" id="img_selector">
<option value="" disabled selected style="display:none;" name="placeholder">Image</option>
<option name="add">Add...</option>
</select>
</div>
答案 0 :(得分:1)
您可以在.change()
功能中移除fill_img_options
来电,在$(this).val("")
内change
内<select>
内change
内<input type="file">
内file
内召唤if
{1}}元素检查fill_img_options()
是否存在<input type="file">
条件,如果将文件名传真为.value
,则将<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div class="form-inline">
<!-- @*hidden element for uploading image*@ -->
<input type="file" id="file_upload" accept=".jpg" style="position: fixed; top: -100em" />
<label for="img_selector">Choose img:</label>
<select class="form-control" id="img_selector">
<option value="" disabled="" selected="" style="display:none;" name="placeholder">Image</option>
<option name="add">Add...</option>
</select>
</div>
<script>
$("#file_upload").change(function() {
const file = $("#file_upload")[0].files[0];
// check if file is selected
if (file) {
var text = file.name.slice(0, -4);
fill_img_options(text);
}
$("#file_upload")[0].value = "";
});
var fill_img_options = function(text) {
$("#img_selector").append(`<option value='${text}'>${text}</option>`);
// remove `.change()` to prevent recursive dispatch of `change` event
$("#img_selector").val(text);
};
$("#img_selector").change(function() {
const selectedName = $(this).find("option:selected").attr("name");
if (selectedName === "add") {
$("#file_upload").click();
// set value attribute to empty string
$(this).val("");
return;
}
})
</script>
</body>
</html>
let arr = ['1','2','0','3','0',undefined,'0',undefined,'3','',''];
// map everything to Number (undefined becomes NaN)
// filter all valid numbers
arr = arr.map(Number).filter(e => !isNaN(e))
console.log(arr);
设置为空字符串
{{1}}