jQuery attr() Metoda

❮ Metody jQuery HTML/CSS

Przykład

Ustaw atrybut szerokości obrazu:

$("button").click(function(){
  $("img").attr("width","500");
});

Definicja i użycie

Metoda attr() ustawia lub zwraca atrybuty i wartości wybranych elementów.

Gdy ta metoda jest używana do zwrócenia wartości atrybutu, zwraca ona wartość PIERWSZEGO dopasowanego elementu.

Gdy ta metoda jest używana do ustawiania wartości atrybutów, ustawia jedną lub więcej par atrybut/wartość dla zestawu dopasowanych elementów.


Składnia

Zwróć wartość atrybutu:

$(selector).attr(attribute)

Ustaw atrybut i wartość:

$(selector).attr(attribute,value)

Ustaw atrybut i wartość za pomocą funkcji:

$(selector).attr(attribute,function(index,currentvalue))

Ustaw wiele atrybutów i wartości:

$(selector).attr({attribute:value, attribute:value,...})

Parameter Description
attribute Specifies the name of the attribute
value Specifies the value of the attribute
function(index,currentvalue) Specifies a function that returns the attribute value to set
  • index - Receives the index position of the element in the set
  • currentvalue - Receives the current attribute value of selected elements

Spróbuj sam - przykłady


Jak zwrócić wartość atrybutu dla elementu.


Jak używać funkcji do ustawiania wartości atrybutu dla elementu.


Jak ustawić wiele atrybutów/wartości dla elementu.


❮ Metody jQuery HTML/CSS