attr()が属性の読み書きに対し、prop()は要素のプロパティの読み書きをする。両者の違いについてはattr()を参照。
prop( propertyName )
引数
- propertyName
- 取得したいプロパティ名
サンプル
jQueryオブジェクトが保持している最初のDOM要素のpropertyNameで指定したプロパティ名のプロパティ値を取得する。
Javascript
$('.jqTest1 .execute1').click(function(e){
$(e.target).parent().find(':radio').each(function(){
if ($(this).prop('checked')) {
alert($(this).val());
}
});
});
$('.jqTest1 .execute2').click(function(e){
$(e.target).parent().find(':radio').each(function(){
if ($(this).attr('checked')) {
alert($(this).val());
}
});
});
HTML
<div class="jqTest1">
<input type="button" value="prop()" class="execute1 btn btn-execute" /> <input type="button" value="attr()" class="execute2 btn btn-execute2" /><br />
<label><input type="radio" name="team" value="鷹" checked="checked" />鷹</label><br />
<label><input type="radio" name="team" value="公" />公</label><br />
<label><input type="radio" name="team" value="猫" />猫</label><br />
<label><input type="radio" name="team" value="檻" />檻</label><br />
<label><input type="radio" name="team" value="鷲" />鷲</label><br />
<label><input type="radio" name="team" value="鴎" />鴎</label>
</div>
.prop( propertyName, value )
引数
- propertyName
- 設定したいプロパティ名
サンプル
jQueryオブジェクトが保持しているDOM要素にプロパティを設定する。
実行結果
Javascript
$('.jqTest2 .execute1').click(function(e){
$(e.target).parent().find(':radio').prop('disabled', true);
});
$('.jqTest2 .execute2').click(function(e){
$(e.target).parent().find(':radio').prop('disabled', false);
});
HTML
<form class="jqTest2">
<input type="button" value="決定" class="execute1 btn btn-execute" /> <input type="button" value="解除" class="execute2 btn btn-execute2" /><br />
<label><input type="radio" name="team" value="鷹" checked="checked" />鷹</label><br />
<label><input type="radio" name="team" value="公" />公</label><br />
<label><input type="radio" name="team" value="猫" />猫</label><br />
<label><input type="radio" name="team" value="檻" />檻</label><br />
<label><input type="radio" name="team" value="鷲" />鷲</label><br />
<label><input type="radio" name="team" value="鴎" />鴎</label>
</form>
.prop( map )
引数
- (object)map
- {プロパティ: プロパティ値, プロパティ: プロパティ値, ...}のようなハッシュを渡すとまとめて設定できる。
.prop( propertyName, function(index, oldPropertyValue) )
functionの戻り値がプロパティ値として設定される。