我正在使用 <input type="file">
从文件资源管理器中选择文件其具有 css 属性 display:none
但我点击<a>
标签将触发 <input type="file">
。下面是我的 HTML 和 JavaScript:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
function BrowseFile() {
$('.attachmentlabel').val('spooky');
$('#file-01').click();
var filePath = $('#file-01').val().split('\\'),
fileName = filePath[filePath.length - 1];
if (fileName !== '' && fileName !== undefined) {
$('.attachmentlabel').val(fileName);
}
}
</script>
</head>
<body>
<input type="file" class="hidden-attachment" id='file-01'> @*the hidden field*@
<input type="text" name="Attachment" class="attachmentlabel"> @*here I want to show the file name*@
<a class="btn attachmnentbtn browse" onclick="BrowseFile()">Browse</a>
</body>
</html>
这里我想做的是如果我点击<a>
它会调用BrowseFile()
该方法会触发<input type="file" class="hidden-attachment">
上的点击事件
我尝试了上面的代码,但这并没有改变 <input type='text'>
的文本内容。我该如何解决这个问题以及原因是什么
最佳答案
添加此代码:
$(document).ready(function(){
$("#file-01").change(function () {
$('.attachmentlabel').val($(this).val())
});
});
您可以简单地处理文件控件的更改事件,并在文本框中更新相同的事件。
检查以下代码
var repassword = "hello";
var password = "hello";
repassword = "hello1";
password = "hello";
function BrowseFile() {
$('.attachmentlabel').val('spooky');
$('#file-01').click();
var filePath = $('#file-01').val().split('\\'),
fileName = filePath[filePath.length - 1];
if (fileName !== '' && fileName !== undefined) {
$('.attachmentlabel').val(fileName);
}
}
$(document).ready(function(){
$("#file-01").change(function () {
$('.attachmentlabel').val($(this).val())
});
});
.hidden-attachment
{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="file" class="hidden-attachment" id='file-01'><br>
<input type="text" name="Attachment" class="attachmentlabel"><br>
<a class="btn attachmnentbtn browse" onclick="BrowseFile()">Browse</a>
关于javascript - 不改变html文本框输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28337812/