2014-02-16 27 views
-1

我想每次单击按钮时添加课程并更改段落中的文本。我怎样才能做到这一点?我对JavaScript很陌生,所以任何帮助将不胜感激!添加课程并更改HTML

HTML 

<h1 id="heading">Hello!</h1> 
<button onClick = "good()">Click Me</button> 

CSS 
.pink{ 
    color:pink; 
} 
.blue{ 
    color:blue;   
} 
.red { 
    color:red; 
} 

JS 


function good(){ 
var computerChoice = Math.random(); 
var heading = document.getElementById('heading'); 


if(computerChoice <= 0.33){ 
    heading.innerHTML = "This is a good!"; 
    heading.addClass(pink); 


    } 
if(computerChoice >= 0.67){ 
    heading.innerHTML = "This is a bad"; 
    heading.addClass(blue); 
    } 
else { 
     heading.innerHTML = "This is else"; 
}  heading.addClass(red); 

} 
+0

对我们而言有何反馈? –

回答

0

.addClass方法在jQuery中可用,不在纯javascript中。您可以使用setAttribute方法设置DOM元素的属性。在这种情况下,您可以设置class属性

heading.setAttribute("class", "pink"); 

您也可以使用.className属性在JavaScript中设置的类名。

heading.className="pink" 

除了这存在一定的误差太大

你所有这一切没有意义,应该是else语句里面的语句后加入红类。

您需要使用else if作为第二条语句,否则您将永远得不到第一条if语句结果。

function good() { 
var computerChoice = Math.random(0, 1); 
alert(computerChoice); 
var heading = document.getElementById('heading'); 
if (computerChoice <= 0.33) { 
    heading.innerHTML = "This is a good!"; 
    heading.setAttribute("class", "pink"); 
} else if (computerChoice >= 0.67) { 
    heading.innerHTML = "This is a bad"; 
    heading.setAttribute("class", "blue"); 
} else { 
    heading.innerHTML = "This is else"; 
    heading.setAttribute("class", "red"); 
} 

}

Js Fiddle Demo

0

看来你正在使用jQuery ..

var heading = $('#heading'); 


if(computerChoice <= 0.33){ 
    heading.html("This is a good!"); 
    heading.addClass(pink); 

} 
1

你非常接近!尽管你有一些错误。

首先是在纯JavaScript(不包括jQuery的),你需要使用.classList.add,而不是.addClass看我记下下面

第二个是,你需要包括周围的类名括号bluepinkred当你添加类

第三是最后.classList.addelse之外,它应该是它里面

第四个是,你需要使用if第一次,else if第二个语句,并else赶上休息

function good() { 
    var computerChoice = Math.random(); 
    var heading = document.getElementById('heading'); 

    if (computerChoice <= 0.33) { 
     heading.innerHTML = "This is a good!"; 
     heading.classList.add('pink'); 
    }  
    else if (computerChoice >= 0.67) { 
     heading.innerHTML = "This is a bad"; 
     heading.classList.add('blue'); 
    } else { 
     heading.innerHTML = "This is else"; 
     heading.classList.add('red'); 
    }  
} 

Demo

一个音符,以及:使用classList.add方法,如果你点击该按钮多次,然后该元素可以具有多个不同类别,例如redblue。文本的颜色会后又在CSS中声明以后,你的情况blue的一个决定会默认在pinkred将默认在bluepink

为了解决这个问题,你可以使用.className = 'red'等代替。这是你应该使用的方法!Demo

0

支持旧浏览器的纯javascript解决方案将使用element.className和“+ =”运算符向该元素添加额外的类。

function good(){ 
var computerChoice = Math.random(); 
var heading = document.getElementById('heading'); 
if(computerChoice <= 0.33){ 
heading.innerHTML = "This is a good!"; 
heading.className+='pink'; 
} 
if(computerChoice >= 0.67){ 
heading.innerHTML = "This is a bad"; 
heading.className +='blue'; 
} 
else { 
heading.innerHTML = "This is else"; 
}  
heading.className +='red'; 
}