jQuery 属性の追加
Sheeraz Gul
2022年6月21日

jQuery attr()
メソッドは、HTML 要素に属性を追加するために使用されます。このチュートリアルでは、jQuery で attr()
メソッドを使用する方法を示します。
jQuery 属性の追加
jQuery の attr()
メソッドを使用して、HTML 要素に属性を追加できます。このメソッドの構文を以下に示します。
$(selector).attr("property", "Value")
ここで
selector
は、ID、クラス、または要素の名前にすることができます。property
は属性の名前です。Value
は属性の値です。
例を試してみましょう:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Add Attribute</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("#attr").click(function(){
$('input[type="checkbox"]').attr("checked", "checked");
});
});
</script>
</head>
<body>
<button type="button" id="attr">Click to Select the Checkbox</button>
<input type="checkbox">
</body>
</html>
上記のコードは、チェックされていないチェックボックスをオンにします。このコードは、attr()
メソッドで要素名セレクターを使用します。このメソッドでは、プロパティがチェックされ、値もチェックされます。
出力を参照してください:
Author: Sheeraz Gul
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
LinkedIn Facebook