0

次のスクリプトを使用して色を設定しています。

<script type="text/javascript">
    if (localStorage.buttonColor) {
        document.getElementsByTagName('html')[0].className = localStorage.buttonColor
    }
    function getButtonColor(buttonName) {
        localStorage.buttonColor = buttonName;
        document.getElementsByTagName('html')[0].className = buttonName
    }
</script>

ここに私のHTMLがあります:

<form class="ng-pristine ng-valid">
   <button name="darkBlue" onclick="getButtonColor(this.name)">Blue</button>
   <button name="black" onclick="getButtonColor(this.name)">Black</button>
</form>

色を選択すると、その色を選択するボタンが無効になり、再度選択できないようにするにはどうすればよいですか? 次に、別のボタンをクリックすると、他のボタンが有効になります。また、localstorage から選択したボタンを無効に設定する必要があります。申し訳ありませんが、以前の質問でこれについて完全に言及していませんでした。

4

4 に答える 4

2
function getButtonColor(button) {
    button.disabled = "disabled"
    localStorage.buttonColor = button.name;
    document.getElementsByTagName('html')[0].className = button.name
}

そして単に送信しますthis

<button name="darkBlue" onclick="getButtonColor(this)">Blue</button>
<button name="black" onclick="getButtonColor(this)">Black</button>

<disclaimer> inline javascript is evil</disclaimer>

于 2013-10-10T13:12:48.157 に答える
0

他の回答 (ハンドラーでボタンを送信するだけ) に加えて、最初に localStorage から色を設定するときにこれを使用できます (「フォーム」が「ボディ」の最初の子であると仮定します)。

if (localStorage.buttonColor) {
    document.getElementsByTagName('html')[0].className = localStorage.buttonColor
    var buttons = document.body.getElementsByTagName('form')[0].getElementsByTagName('button')
    for(var i =0; i < buttons.length; i++)
        if(buttons[i].name == localStorage.buttonColor) button.disabled = true
}

getElementsByTagName の選択が冗長になる可能性があるため、コード内の要素を頻繁に検索する必要がある場合は、jQuery の使用を検討することをお勧めします。

于 2013-10-10T13:20:09.140 に答える
0

これを使用して、変数 (多くの場合) にバインドすることをお勧めします。これで、関数を呼び出した html オブジェクトを取得します。

http://www.quirksmode.org/js/this.html https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

 function getButtonColor() {
        var that = this; 
        localStorage.buttonColor = that.Name;
        document.getElementsByTagName('html')[0].className = that.Name; 
        that.disabled = "disabled"; 
    }
于 2013-10-10T13:30:09.217 に答える