いくつかの入力フィールドがある Web ページがあります。私がやりたいことは、今回フィールドの 1 つを選択した場合、Web ページは次回のロード時に同じフィールドに自動的にフォーカスする必要があるということです。
クッキーが進むべき道だと想像できます。私が理解できないのは、Cookie を介して特定の入力フィールドに「オートフォーカス」などの属性を追加する方法です。
どんな助けでも素晴らしいでしょう。ティア、ニキル
いくつかの入力フィールドがある Web ページがあります。私がやりたいことは、今回フィールドの 1 つを選択した場合、Web ページは次回のロード時に同じフィールドに自動的にフォーカスする必要があるということです。
クッキーが進むべき道だと想像できます。私が理解できないのは、Cookie を介して特定の入力フィールドに「オートフォーカス」などの属性を追加する方法です。
どんな助けでも素晴らしいでしょう。ティア、ニキル
@Nathan Wallace のアイデアに基づいて、別の方法で自分の質問を解決しました。
まず、javascript を挿入して、問題の入力フィールドをドキュメント Cookie に追加します。
$(this).click(function(event) {
if($(event.target).is(":input")){
event.preventDefault();
document.location = "this-clicked:"+window.location;
// this is the function which writes the cookie
writeCookie(event)
}
});
関数 writeCookie() 自体を上記の if ステートメント内に記述することもできましたが、私はさまざまなものを分けておくのが好きです。それ以外の場合、writeCookie 関数は次のようになります。
function writeCookie(event) {
var expirationTime = new Date();
expirationTime.setTime(expirationTime.getTime() + EXPTIME);
document.cookie="focusOnMe=" +
escape(event.target.id) +
"; expires="+expirationTime.toGMTString();
}
以上が今回のセッションです。これで、ページが読み込まれるたびに、Cookie が存在するかどうかを確認します
function readElementFromCookie() {
var allcookies = document.cookie;
// 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];
if (name == "focusOnMe") {
return value;
}
}
}
そして、この関数が空でない値を返す場合、次のようにして Web ページをその要素にフォーカスさせます。
ELEM = readElementFromCookie();
if (ELEM) {
javascript: document.getElementById("ELEM").focus();
}
もちろん、同じように、先に設定した Cookie を強制的に失効させて、流れを一方向に保つこともできます。
ニキル