Domanda

Un po 'nuovo in jQuery, quindi scusa il tentativo di identificare correttamente le cose.

Ho bisogno che l'ID di un elemento si rifletta in un selettore che funzioni in profondità una coppia, e non sono sicuro di come farlo.

$("input[type='file'][id^='pic_']").change(       //I need this element's id...
    function()
    {
        $("."+this.id).hide("fast",
            function()
            {
                //..to be reflected in this class selector
                $("."+this.id).attr("checked", true);
            }
        );
    }
);

Grazie per l'aiuto in anticipo. : -)

È stato utile?

Soluzione

Usa le chiusure per portare una variabile con l'id all'interno dell'ambito della funzione più interna.

$("input[type='file'][id^='pic_']").change(       //I need this element's id...
        function()
        {
                var fileSelector = "." + this.id;
                $(fileSelector).hide("fast",
                        function()
                        {
                                //..to be reflected in this class selector
                                $(fileSelector).attr("checked", true);
                        }
                );
        }
);

Altri suggerimenti

La variabile this in un callback di evento è l'elemento DOM che ospita l'evento. Nel callback della funzione change, questo è l'elemento cambiato. Pertanto:

$("input[type='file'][id^='pic_']").change(
  function() {
    $(this).hide("fast",
      function() {
        $(this).attr("checked", true);
      }
    }
  }
}

Sembra una domanda di portata variabile:

$("#my_input").change(function() {
    var my_id = $(this).attr('id');
    $(this).hide('fast', function() {
        alert(my_id); // Will show an alert with the id from above.
        alert($(this).attr('id')); // *Should* show an alert with the same id.
    });
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top