我有一个复选框,我想在选中它时运行一个函数,在未选中它时运行另一个函数。我的代码是:
function showCustomer(str,str2) {
if (document.getElementById(str).checked) {
var xhttp;
if (str == "") {
document.getElementById("xxxx").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("xxxx").innerHTML = this.responseText;
}
};
xhttp.open("GET", "add.jsp?q=" + str + "&q2=" + str2, true);
xhttp.send();
}
else {
var xhttp;
if (str == "") {
document.getElementById("xxxx").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("xxxx").innerHTML = this.responseText;
}
};
xhttp.open("GET", "minus.jsp?q=" + str + "&q2=" + str2, true);
xhttp.send();
}
}
我的复选框代码是:
<input id="<%=cheque_tbl.getPRICE()%>" class="ch" type="checkbox" name="<%=cheque_tbl.getCHECKID()%>" onchange="showCustomer(this.value,this.id)">
问题是 document.getElementById(str).checked
不起作用,必须是 document.getElementById("str").checked
但我的复选框 id不是一个简单的字符串,而是一个变量。
如何在 getelement
中使用 var?为什么我的代码不起作用?
最佳答案
HTML 更改:绑定(bind)复选框范围以通过 onchange 函数中的“this”访问它
<input id="dd" class="ch" type="checkbox" name="dd" onchange="showCustomer.apply(this,[this.value,this.id])">
JS 更改:
function showCustomer(str,str2) {
if (this.checked) {
var xhttp;
if (str == "") {
document.getElementById("xxxx").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("xxxx").innerHTML = this.responseText;
}
};
xhttp.open("GET", "add.jsp?q=" + str + "&q2=" + str2, true);
xhttp.send();
}
else {
var xhttp;
if (str == "") {
document.getElementById("xxxx").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("xxxx").innerHTML = this.responseText;
}
};
xhttp.open("GET", "minus.jsp?q=" + str + "&q2=" + str2, true);
xhttp.send();
}
}
希望它有助于解决复选框的 Document.getElementById() 问题
关于javascript - 发送一个变量到jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40100384/