无法将样式应用于其单击事件上的按钮



我在HTML5+Javascript中动态创建了一个按钮。我已为该按钮分配了一个单击事件。当我点击它时,它是内容&背景颜色应该改变。内容变化很好,但背景色没有变化。

我的代码是;

<style>
.selectBtn{ height:60px;width:80px;background-color:yellow; }
</style>
<script>
var container = document.getElementById('abc');
function dx(){
var Btn = document.createElement('button');
Btn.type = 'button';
Btn.className = 'selectBtn';
Btn.innerHTML = 'SUBMIT';
container.appendChild(Btn);
Btn.onclick = function()
{
this.innerHTML='voted';
this.style.backgroundColor:'blue';
}
dx();
</script>
<body><div id='abc'></div></body>

使用=而不是colon。使用此:-

this.style.backgroundColor = "#f47121";

你不想改变

var container = document.getElementById('abc');
function dx(){
   var Btn = document.createElement('button');
   Btn.className = 'selectBtn';
   Btn.innerHTML = 'SUBMIT';
   container.appendChild(Btn);
   Btn.onclick = function() {
      this.innerHTML='voted';
      this.style.backgroundColor = 'blue';
   }
}

我不确定Btn.type = 'button';是否有效,但它毫无意义在要将:更改为=的样式上,只能在对象中使用:

此外,您可能不希望使用textContent而不是innerHTML

我忍不住展示了我是如何做到这一点的,只是为了好玩,以及它的教育目的。

window.onload = function(){
    (function(){
        var doc = document; 
        var get = function(id){return doc.getElementById(id);};
        var inject = function(el,str){el.innerHTML = str;return el;};
        inject(get('content'),'<button type="button" id="btn-select">SUBMIT</button>');
        get('btn-select').onclick = function(){inject(this,'Voted!').className = 'voted';};
    })();
};

演示:http://jsfiddle.net/ZNfBe/

最新更新