我正在使用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>
最佳答案
尝试这个:
<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>