如何在jquery中的load函数中添加一个新类?

时间:2017-01-31 13:13:09

标签: jquery html

我希望如果文件扩展名为.jpg,则将新类分配给按钮并隐藏文本框。关于flie load函数这是我的代码我做错了什么?

HTml

<form  method="post" enctype="multipart/form-data">
   Select image to upload:
   <input type="file" class="flUpload" name="image" id="fileToUpload image">
   <input type="text" class='result' id='result'/>
   <input type="submit" class="btnClick" id='btn' value="Upload Image" name="submit">
</form>

PHP

<?php
if(isset($_POST['submit']))
{
  $target_dir = "uploads/";
  $target_file = $target_dir . basename($_FILES["image"]["name"]);
  $uploadOk = 1;
  $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

  if (!move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
   echo "Sorry, there was an error uploading your file.";
  }
}
?>

的jQuery

 <script>
 $(function () {
  $('#image').load(function () {
    if ($('.flUpload').val() != '') {
      var file = $('.flUpload')[0].files[0];
      var fileName = file.name;
      var fileExt = '.' + fileName.split('.').pop();
      if(fileExt == ".jpg"){
        alert(fileExt);
        $(".result").hide();
        $(".btnClick").addClass('newclass');
      }
    }
    else {
     alert('Please select a file.')
    }
  });
});
</script>

1 个答案:

答案 0 :(得分:2)

您输入了错误的id文件选择器,您需要将活动名称更改为change

$(function () {
  $('input[name="image"]').change(function () {
        //............
  });
});

Working fiddle

它会帮助你。