0
$(document).ready(function()
{
    mais_telefones();
    upload_imagens();
});

function mais_telefones()
{
    mais_telefones.click(function(event)
    {
        var label = input = button = null,
            labels = $('.telefones'),
            tamanho = labels.length;

        event.preventDefault();

        if (tamanho < 3)
        {
            label = $('<label for="elemento' + tamanho +
                '" class="telefones elemento' +
                tamanho + '">Telefone</label>');

            input = $('<input id="elemento' + tamanho +
                '" class="elemento' +
                tamanho + '"type="text" name="telefones[]" />');

            button = $('<button class="elemento' + tamanho + '">X</button>');

            button.click(function(event)
            {
                event.preventDefault();
                $('.elemento' + tamanho).remove();
            });

            label.insertBefore($(this));
            input.insertBefore($(this));
            button.insertBefore($(this));
        }
    });
}

function upload_imagens()
{
    var imagem = $('#imagem');
    imagem.change(function(event)
    {
        alert($(this).files);
    });
}

In mais_telefones function, I can use $(this), append elements (appendChild), insertBefore, etc. But in the second function I can't. $(this).files returns undefined but this.files returns the values... What's wrong?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
htom
  • 1
  • 1

3 Answers3

0

you have to pass what $(this) is into the individual functions

for example:

mais_telefones($('div'));

and in the mais_telefones function:

function mais_telefones(sel){
     this = sel.get(0);
     ...
}
Naftali
  • 144,921
  • 39
  • 244
  • 303
  • but why it works in the first function and not in the second one? Thank you. – htom Mar 14 '11 at 17:57
  • what is `$(this).files` supposed to do? i have never heard of that function – Naftali Mar 14 '11 at 18:08
  • it's not a jquery function. he's trying to access the native dom element which does contain a "files" collection for inputs of type="file" – fehays Mar 14 '11 at 18:15
0

jQuery: What's the difference between '$(this)' and 'this'? this could probably help you. excuse the pun :P

Community
  • 1
  • 1
corroded
  • 21,406
  • 19
  • 83
  • 132
0

jquery always returns an array of jquery objects. You probably want this:

$(this)[0].files;
fehays
  • 3,147
  • 1
  • 24
  • 43
  • do you know why? When i say "this", i want the current object. In my first function I'm using this in insertBefore, take a look please. Thank you. – htom Mar 14 '11 at 18:05
  • It's because $(this) returns a jquery object which does not contain a "files" collection. You want the native javascript element and to do that you have to treat $(this) as an array. .insertBefore() works because it's a jquery function – fehays Mar 14 '11 at 18:11