我正在學習JavaScript的基礎知識,但仍然弄錯了一些基礎知識,並試圖使其工作,但失敗。我試圖在選中某個單選按鈕時使消息更改字體重量。的jsfiddle:http://jsfiddle.net/Eg87P/如何使單選按鈕在JavaScript中工作?
HTML/JavaScript代碼:
<div id="prob2">
<h1>Radio Buttons</h1>
<p id="msg">Message</p>
<input type="radio" value="bold" name="rdFontStyle" id="bold"/>Bold<br/>
<input type="radio" value="italic" name="rdFontStyle" id="italic"/>Italic<br/>
<input type="radio" value="underline" name="rdFontStyle" id="underline"/>Underline<br/>
<input type="radio" value="regular" name="rdFontStyle" id="regular"/>Regular<br/>
<script type="text/javascript">
function msg1
{
var msg = document.getElementById("msg");
if(document.getElementById("bold").checked)
{
if(msg.hasAttribute("style"))
{
msg.removeAttribute("style");
}
msg.style.fontWeight = "bold";
}
else if(document.getElementById("italic").checked)
{
if(msg.hasAttribute("style"))
{
msg.removeAttribute("style");
}
msg.style.fontWeight = "italic";
}
else if(document.getElementById("underline").checked)
{
if(msg.hasAttribute("style"))
{
msg.removeAttribute("style");
}
msg.style.fontWeight = "underline";
}
else if(document.getElementById("regular").checked)
{
if(msg.hasAttribute("style"))
{
msg.removeAttribute("style");
}
msg.style.fontWeight = "normal";
}
}
msg1();
</script>
</div>
您必須將更改事件綁定到單選按鈕,在此更改事件中,您可以調用msg1()方法。 – Hatsjoem