我正在使用javascript。但它不能正常工作。 javascript用于将复选框中的值传递给查询字符串。
这是我的代码,请帮我找出错误。
<script type="text/javascript">
function GetOS() {
$('input[type="checkbox"]').on('change', function (e) {
var data = {},
fdata = [],
loc = $('<a>', { href: window.location })[0];
$('input[type="checkbox"]').each(function (i) {
if (this.checked) {
if (!data.hasOwnProperty(this.name)) {
data[this.name] = [];
}
data[this.name].push(this.value);
}
});
$.each(data, function (k, v) {
fdata[k] = [v.join(',')];
});
fdata = fdata.join('&');
$.post('/ajax-post-url/', fdata);
if (history.pushState) {
history.pushState(null, null, loc.pathname + '?' + fdata);
}
});
}
window.onload = GetOS;
</script>
<div class="panel-body">
<div class="rowElem">
<input type="checkbox" name="chbox" id="" value="Color #1" />
<label>Color #1</label>
</div>
<div class="rowElem">
<input type="checkbox" name="chbox" id="" value="Color #2" />
<label>Color #2</label>
</div>
<div class="rowElem">
<input type="checkbox" name="chbox" id="" value="Color #3" />
<label>Color #3</label>
</div>
</div>
答案 0 :(得分:1)
试试这个:
<script type="text/javascript">
function GetOS() {
console.log("rom");
$('input[type="checkbox"]').on('change', function (e) {
var data = {},
fdata = [],
loc = $('<a>', { href: window.location })[0];
$('input[type="checkbox"]').each(function (i) {
if (this.checked) {
if (!data.hasOwnProperty(this.name)) {
data[this.name] = [];
}
data[this.name].push(this.value);
}
});
// get the key
var key = Object.keys(data)[0];
// and the data
// it works to without joining
var fdata = key+"="+data[key].join(',');
// and if you wanna strip the whitespaces
// use fdata = fdata.replace(/\s/g,"");
$.post('/ajax-post-url/', fdata);
if (history.pushState) {
history.pushState(null, null, loc.pathname + '?' + fdata);
}
});
}
window.onload = GetOS;
</script>
答案 1 :(得分:1)
这也可行
<script type="text/javascript">
function GetOS() {
$('input[type="checkbox"]').on('change', function (e) {
var data = {},
fdata = [],
qs = "",
loc = $('<a>', { href: window.location })[0];
$('input[type="checkbox"]').each(function (i) {
if (this.checked) {
if (!data.hasOwnProperty(this.name)) {
data[this.name] = [];
}
data[this.name].push(this.value);
}
});
$.each(data, function (k, v) {
fdata.push(k + "=" + v.join(','));
});
qs = fdata.join('&');
$.post('/ajax-post-url/', fdata);
if (history.pushState) {
history.pushState(null, null, loc.pathname + '?' + qs);
}
});
}
window.onload = GetOS;
</script>