クッキーを設定し、JavaScriptでクッキーを取得するにはどうすればよいですか?
Cookieを作成する最も簡単な方法は、次のような文字列値をdocument.cookieオブジェクトに割り当てることです。
document.cookie = "key1=value1;key2=value2;expires=date";
ここで、「expires」属性はオプションです。この属性に有効な日付または時刻を指定すると、Cookieは指定された日付または時刻に期限切れになり、それ以降はCookieの値にアクセスできなくなります。
次のことを試してください。入力Cookieに顧客名を設定します。
ライブデモ
<html>
<head>
<script>
<!--
function WriteCookie() {
if( document.myform.customer.value == "" ) {
alert("Enter some value!");
return;
}
cookievalue= escape(document.myform.customer.value) + ";";
document.cookie="name=" + cookievalue;
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>
</body>
</html> document.cookieオブジェクトの値はcookieであるため、cookieの読み取りは書き込みと同じくらい簡単です。したがって、Cookieにアクセスするときはいつでも、この文字列を使用できます。 document.cookie文字列は、名前=値のペアのリストをセミコロンで区切って保持します。ここで、nameはCookieの名前であり、valueはその文字列値です。
ライブデモ
<html>
<head>
<script>
<!--
function ReadCookie() {
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++) {
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
document.write ("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<p> click the following button and see the result:</p>
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html> -
trタグからidを取得し、JavaScriptを使用して新しいtdに表示するにはどうすればよいですか?
以下が私たちのテーブルだとしましょう- <table> <tr id='StudentDetails'> <th>StudentName</th> <th>StudentCountryName</th> </tr> <tr id='FirstRow'> <td&
-
JavaScriptでCSS変数を取得および設定する
getComputedStyle()メソッドは、ターゲット要素に適用されたすべてのスタイルを含むオブジェクトを提供します。 getPropertyValue()メソッドは、計算されたスタイルから目的のプロパティを取得するために使用されます。 setProperty()は、CSS変数の値を変更するために使用されます。 例 次の例は、JavaScriptを使用してCSS変数を取得および設定する方法を示しています。 <!DOCTYPE html> <html> <head> <style> :root { --outerCo