【发布时间】:2011-06-02 03:10:09
【问题描述】:
我有一个文本字段,它的更改事件绑定到一个验证文本字段值的函数,并可能将相应的验证错误消息拼接到文本字段上方的 DOM 中。如果通过单击一对有些不相关的单选按钮中的一个触发更改事件,则单击的单选按钮会获得焦点,但与我和用户的期望相反,它没有被选中 - 这就是问题所在。
虽然最终系统中的验证会在服务器端使用AJAX进行,但下面的代码说明AJAX与问题无关。
你能告诉我我在这里缺少什么吗:
<html>
<head>
<STYLE type="text/css">
.highlighted { color: red; }
</STYLE>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
</head>
<body>
<span id="errors">
</span>
<label for="mytextfield">First, type something in this textfield</>
<input type="text" id="mytextfield" name="mytextfield"/>
<p>Second, click on one of these radio buttons</>
<INPUT TYPE="radio" NAME="binaryquestion" VALUE="Y" >Yes</>
<INPUT TYPE="radio" NAME="binaryquestion" VALUE="N" >No</>
<script type="text/javascript">
$(document).ready(function() {
//$("#mytextfield").change(validateTextField);
$("#mytextfield").change(spliceInTheValidationResultMessage);
});
function validateTextField() {
$.ajax({
url: 'http://www.google.com',
success: function(data) {
spliceInTheValidationResultMessage();
}
});
}
function spliceInTheValidationResultMessage() {
$("#errors").append("<p>Thank you for your input!</p>").addClass("highlighted");
alert("I expect the radio button that you clicked to become checked. However, close this dialog and you'll see that it will have gained the focus but is NOT checked!");
};
</script>
</body>
</html>
【问题讨论】:
-
试图改变单选按钮状态的代码在哪里?我看不到。
-
没有这样的代码。如果您将页面加载到浏览器中并单击其中一个单选按钮,问题是单选按钮是否被选中取决于您没有首先在文本字段中输入内容。
-
对问题定义的进一步细化:问题是单选按钮是否被选中取决于您没有事先在文本字段中输入内容。
标签: dom radio-button jquery-events checked mutation-events