我有一個使用 Ajax 進行查詢的頁面。此頁面上的復選框無需任何 URL 即可作業。我想要做的是能夠使用 URL 加載此資料。所以當我在 url 中輸入一個值時,我希望該資料自動出現。
$checkboxes = $('input[type=checkbox');
$checkboxes.change(function(){
window.location.hash = 'marka=' $checkboxes.filter(':checked').map(function(){
return this.value;
}).get().join(",");
console.log(window.location.hash);
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="custom-control custom-checkbox">
<input class="custom-control-input common_selector marka" type="checkbox" id="marka_1" value="1">
<label class="custom-control-label cz-filter-item-text" for="marka_1">Value 1 </label>
<input class="custom-control-input common_selector marka" type="checkbox" id="marka_2" value="2">
<label class="custom-control-label cz-filter-item-text" for="marka_21">Value 2 </label>
<input class="custom-control-input common_selector marka" type="checkbox" id="marka_3" value="3">
<label class="custom-control-label cz-filter-item-text" for="marka_3">Value 3 </label>
<input class="custom-control-input common_selector marka" type="checkbox" id="marka_4" value="4">
<label class="custom-control-label cz-filter-item-text" for="marka_4">Value 4 </label>
</div>
我想通過 URL 加載資料
uj5u.com熱心網友回復:
如果我理解正確,您希望將復選框狀態保存到散列中,然后在有人訪問散列中包含復選框資訊的 URL 時再次加載它。
您已經有了將復選框狀態保存到哈希的代碼。您正在使用一個簡單的逗號分隔串列,例如#marka=2,4. 加載資料很簡單:
window.location.hash用;讀取哈希- 洗掉
#; - 洗掉
marka=,這樣你就只剩下value選中的復選框的 s 了; - 創建一個包含剩余值的陣列;
- 遍歷所有復選框并檢查其值在該陣列中的復選框;
是這樣的:
function loadCheckboxState() {
// Get the hash, and remove the '#', we are left with marka=2,4
let string = window.location.hash.substring(1);
// Remove 'marka=', so we are left with 2,4
string.replace('marka=', '');
// Create an array of the ids left, [2,4]
let checked = string.split(',');
// Now check the checkboxes whose value is in the array
$checkboxes.prop('checked', function () {
return checked.indexOf(this.value) >= 0;
});
}
您可以在頁面加載時運行它,例如:
$(document).ready(function() {
loadCheckboxState();
});
請注意,您的代碼中存在一些小問題:
jQuery 1.9.1 很古老(2013 年!),您應該使用更新的版本;
錯別字:
$('input[type=checkbox');錯別字:
for="marka_21";使用
var(或let) 來宣告你的變數;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/535343.html
