[英]On click, set cookie and check checkbox
我有一個帶有復選框的屏幕。 單擊標簽后,將打開一個新窗口,其中包含文本和一個同意按鈕。 用戶單擊“同意”按鈕后,將設置一個具有唯一ID的Cookie,該ID會引用該復選框。 如何根據Cookie是否等於1來選中此復選框? 代碼如下。
document.cookie = "doc_35_readit=0";
$('#have_read_agreement').on('click', function () {
document.cookie = "doc_35_readit=1";
});
現在,當窗口關閉時,我不確定如何選中該復選框。 像這樣的東西?
if (cookie("doc_35_readit") == "1") {
$(".doc_35_readit").click();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Initial checkbox: -->
<input type="checkbox"
id="agreementChecker-0"
name="agreeCheck-0"
value="35"
class="mandatory agreeChecker doc_35_readit"/>
<!-- New Window opens with text, button at bottom: -->
<p align="center" id="have_read_agreement" style="text-align:center;font-size:20px;">
<a href="javascript:window.close()" class="btn-read">I have read this agreement and accept all terms and conditions.</a>
</p>
您可以將input:checkbox元素的checked
屬性設置為true或false(如果您希望將其相應地選中或取消選中)。
$('input[name=test]').attr('checked', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" name="test" />
要按名稱獲取cookie,您需要創建自己的get
函數,例如:
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
這將解析cookie,並使您能夠按名稱從它們中進行選擇,例如:
getCookie("doc_35_readit")
然后,您的情況將如下所示:
if (getCookie("doc_35_readit") == "1") {
$(".doc_35_readit").click();
}
僅使用本地javascript很有可能。
但由於您似乎不擅長創建cookie,而您正在使用jquery
我建議您使用此插件: https : //github.com/js-cookie/js-cookie
那么您可以嘗試以下示例:
<button id="delete">delete cookie</button>
<button id="display">display cookie</button>
<textarea></textarea>
<div id="modal"><h1>this will display only if user not accept yet</h1>are you agree with our ToS? <input type="checkbox" id="agreementChecker-0" name="agreeCheck-0" value="35" class="mandatory agreeChecker doc_35_readit"></div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<script>
$(function(){
$('#agreementChecker-0').change(function(){
if($(this).prop('checked')){
Cookies.set('doc_35_readit', 1);
$('#modal').hide();
}else{
Cookies.set('doc_35_readit', 0);
$('#modal').show();
}
});
if(Cookies.get('doc_35_readit')== 1){
$('#modal').hide();
}
$('#display').click(function(){
var c = (Cookies.get('doc_35_readit') ==undefined) ? 'not found':Cookies.get('doc_35_readit');
$('textarea').val(c);
console.log(Cookies.get()); //show all possible cookie in console
});
$('#delete').click(function(){
Cookies.remove('doc_35_readit');
$('#modal').show();
});
});
</script>
PS:您可以嘗試刷新頁面以查看是否已設置Cookie。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.