如何在单击后禁用按钮

时间:2013-10-10 13:10:13

标签: javascript

我使用以下脚本设置颜色:

<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 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

除了其他答案(只是发送处理程序中的按钮),你可以在最初设置localStorage的颜色时使用它(假设你的'form'是'body'的第一个孩子):

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
}

如果您经常需要在代码中查找元素,可能需要考虑使用jQuery,因为getElementsByTagName选项可能会变得冗长。

答案 2 :(得分:0)

您也可以使用:

function getButtonColor(button) {        
var elem=documentt.getElementById(button.id);
elem.removeAttribute("onclick");
}

答案 3 :(得分:0)

首选使用 this 并将其绑定到变量(通常是那个)。 在这里你得到了调用该函数的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"; 
    }