感谢您查看我的问题。如何使用Javascript在表单中选择文件时更改标签文本
我问类似这样的前手在下面的链接的问题。不幸的是,给出的答案适用于代码片段,但不适用于我的网站。我创建了一个空白的HTML文档,并在其中插入了以下代码。我想要做的基础是这个。文件输入标签将使用CSS隐藏。然后我使用标签来接管输入标签的控制。一旦选择了一个文件,我希望文件名(不是路径)显示在标签内,并且也保持图像对用户可见。正如我在上一个问题中所述,我不希望使用jQuery。预先感谢您看看我的代码并提供帮助!
继承人我刚才的问题:How do I change HTML Label Text Once File Has Been Selected using Javascript
继承人的代码我的“index2.php”文件:
<html>
<head>
<script>
var profilePic = document.getElementById('profilepic'); /* finds the input */
function changeLabelText() {
var profilePicValue = profilePic.value; /* gets the filepath and filename from the input */
var fileNameStart = profilePicValue.lastIndexOf('\\'); /* finds the end of the filepath */
profilePicValue = profilePicValue.substr(fileNameStart + 1); /* isolates the filename */
var profilePicLabelText = document.querySelector('label[for="profilepic"]').childNodes[2]; /* finds the label text */
if (profilePicValue !== '') {
profilePicLabelText.textContent = profilePicValue; /* changes the label text */
}
}
profilePic.addEventListener('change',changeLabelText,false); /* runs the function whenever the filename in the input is changed */
</script>
</head>
<body>
<div class="changepic-wrap">
<form action="changepicauth.php" method="post">
<input type="file" name="profilepic" id="profilepic" class="inputfile">
<br>
<label for="profilepic">
<img src="#" />
Upload Picture...
</label>
<br>
<div class="button-wrap">
<button>Change Picture</button>
</div>
</form>
</div>
</body>
</html>
包装你 “上传图片” 用' ...'并改变其'innerHTML'。 –
我不想使用标签。感谢您的建议,但那不是我想要做的。 –