2011-12-04 136 views
4

如何將以下代碼轉換爲Unobtrusive JavaScript?當用戶選擇一個按鈕radion使用Unobtrusive JavaScript創建單選按鈕

<!DOCTYPE html> 
<html> 
<head> 
    <title>title</title> 
    <script type="text/javascript"> 
     function ar_change(){ 
      if (document.ar_form.ar_type[0].checked) 
       var txt = ""; 
      else if (document.ar_form.ar_type[1].checked) 
       var txt = "first text."; 
      else if (document.ar_form.ar_type[2].checked) 
       var txt = "second text."; 
      else if (document.ar_form.ar_type[3].checked) 
       var txt = "third text."; 
      else if (document.ar_form.ar_type[4].checked) 
       var txt = "forth text."; 
      document.ar_form.ar_text.value=txt; 
     } 
    </script> 
</head> 
<body> 
    <form name="ar_form" action="." method="post"> 
     <textarea name="ar_text"></textarea><br> 
     <input type="radio" name="ar_type" value="0" onclick="ar_change()" checked>no text<br> 
     <input type="radio" name="ar_type" value="1" onclick="ar_change()">text 1<br> 
     <input type="radio" name="ar_type" value="2" onclick="ar_change()">text 2<br> 
     <input type="radio" name="ar_type" value="3" onclick="ar_change()">text 3<br> 
     <input type="radio" name="ar_type" value="4" onclick="ar_change()">text 4<br> 
     <input type="submit" /> 
    </form> 
</body> 
</html> 

該JavaScript改變內容。當前腳本正在工作,我想從標籤中刪除所有「onclick」,並檢查它使用js更改了redio按鈕。我怎麼做?

回答

2

需要(除了用於去除onclick處理程序)未更改的形式:

平原JS:

DEMO here

window.onload=function() { 
    var rads = document.getElementsByName("ar_type"); 
    for (var i=0,n=rads.length;i<n;i++) { 
    rads[i].onclick=function() { 
     this.form.ar_text.value=["","first_txt","second_txt","third_txt","fourth_txt","fifth_txt"][this.value]; 
    } 
    if (rads[i].checked) rads[i].click(); // set the value onload 
    } 
} 

的jQuery:

DEMO

$(document).ready(function() { 
    $('input[name=ar_type]:radio').click(function() { 
    this.form.ar_text.value=["","first_txt","second_txt","third_txt","fourth_txt","fifth_txt"][this.value]; 
    }); 
    $('input[name=ar_type]:radio').filter(":checked").click(); // IMPORTANT!!! 
}); 
+0

看起來不錯,演示如期工作 – Rami

+0

我怎麼用JQuery來做? – Rami

0
var artexts = [ 
    "", 
    "first text.", 
    "second text.", 
    "third text.", 
    "forth text." 
]; 
ondocumentload(function() { // use any known library thing or your owns 
    var radios = document.getElementsByName("ar_type"); 
    for (var i=0; i<radios.length; i++) 
     radios[i].addEventListener("change", function() { 
      for (var i=0; i<radios.length; i++) 
       if (radios[i].checked) 
        document.getElementById('txtarea').value = artexts[radios[i].value]; 
     }, false); 
}); 

請勿在您的html中使用* -attributes。

+0

錯誤的選擇器。 getElementsByName(「art_type」)或getElementsByTagName(「input」) – mplungjan

+0

謝謝,我怎麼能混合起來:-(固定。 – Bergi