【发布时间】:2013-04-25 13:51:17
【问题描述】:
我可以对这段代码使用一些帮助。
我创建了一个小提琴来显示这个问题 - http://jsfiddle.net/r4hqC/
我正在尝试读取 2 个无线电组的值,然后通过 GET 请求 (Ajax) 发送它们的值。
该代码在第一次单选按钮单击时有效,其中单选按钮的值返回为未定义,直到单选按钮更改。这在两组中都会发生。
代码如下:
function jsdatabaseMatch()
{
$(document).ready(function(){
$(".form1").change(function () {window.vala = $('.form1:checked').val(); //Radio group 1
$(".form2").change(function () {window.valb = $('.form2:checked').val(); //Radio group 2
});
});
});
alert(window.vala); //Radio 1 contains..
alert(window.valb); //Radio 2 contains..
var getr = window.vala + "&pricerange=" + window.valb; //GET request
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","showcase.php?yes="+getr,false); //Prepare GET Request
xmlhttp.send();
document.getElementById("pricecompare").innerHTML=xmlhttp.responseText;
}
我试过用.click替换.change,结果是一样的。
提前致谢。
由 tymeJV 解决
- 从执行
jsdatabaseMatch的 HTML 中删除了onclick触发器。 - 在 jQuery 中执行
function jsdatabaseMatch()广播.change事件。
这里是:
$(document).ready(function(){
$(".form1").change(function () {window.vala = this.value;}); //Radio group 1
$(".form1").change(jsdatabaseMatch); //Radio group 1
$(".form2").change(function () {window.valb = this.value;}); //Radio group 2
$(".form2").change(jsdatabaseMatch); //Radio group 2
});
function jsdatabaseMatch()
{
alert(window.vala);
alert(window.valb);
var getr = window.vala + "&pricerange=" + window.valb; //GET request
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","showcase.php?yes="+getr,false); //Prepare GET Request
xmlhttp.send();
document.getElementById("pricecompare").innerHTML=xmlhttp.responseText;
}
【问题讨论】:
-
为什么是
.form1:checked?如果元素没有被检查,那么你会得到 undefined 因为选择器不存在