使用无干扰JavaScript的窗体单选按钮

Form Radio Buttons with Unobtrusive JavaScript

本文关键字:窗体 单选按钮 JavaScript 干扰      更新时间:2023-09-26

如何将以下代码转换为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按钮。我该怎么做?

不需要更改表单(除了删除onclick处理程序(:

普通JS:

演示

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:

演示

$(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!!!
});
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中使用on*属性。