jQuery prop () Metode

Metode HTML/CSS jQuery

Contoh

Tambah dan hapus properti bernama "warna":

$("button").click(function(){
  var $x = $("div");
  $x.prop("color", "FF0000");
  $x.append("The color property: " + $x.prop("color"));
  $x.removeProp("color");
});

Definisi dan Penggunaan

Metode prop() menyetel atau mengembalikan properti dan nilai elemen yang dipilih.

Ketika metode ini digunakan untuk mengembalikan nilai properti, metode ini mengembalikan nilai elemen yang cocok PERTAMA.

Ketika metode ini digunakan untuk menyetel nilai properti, metode ini menetapkan satu atau lebih pasangan properti/nilai untuk set elemen yang cocok.

Catatan: Metode prop() harus digunakan untuk mengambil nilai properti, misalnya properti DOM (seperti tagName, nodeName, defaultChecked) atau properti buatan Anda sendiri.

Tip: Untuk mengambil atribut HTML, gunakan metode attr() sebagai gantinya.

Tip: Untuk menghapus properti gunakan metode removeProp() .


Sintaksis

Mengembalikan nilai properti:

$(selector).prop(property)

Tetapkan properti dan nilainya:

$(selector).prop(property,value)

Tetapkan properti dan nilai menggunakan fungsi:

$(selector).prop(property,function(index,currentvalue))

Tetapkan beberapa properti dan nilai:

$(selector).prop({property:value, property:value,...})

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

Cobalah Sendiri - Contoh


prop() dan attr() mungkin mengembalikan nilai yang berbeda. Contoh ini menunjukkan perbedaan saat digunakan untuk mengembalikan status "dicentang" dari kotak centang.


Metode HTML/CSS jQuery