如何将以下代码转换为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>
当用户选择一个radion按钮时,此javascript会更改内容。当前脚本工作我想从标签中删除所有“onclick”,并检查使用js更改的redio按钮。我该怎么做?
答案 0 :(得分:2)
不需要更改表单(除了删除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!!!
});
答案 1 :(得分: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。