2014-02-16 26 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'; 
}