javascript - Less redundant way of putting this -
i have code stores checked value of checkbox in localstorage.
how shrink it?
$('#ospone').click(function(e){ savesettings(e["currenttarget"]["id"], e["currenttarget"]["checked"]); getsettings(e["currenttarget"]["id"]); }); $("#osptwo").click(function(e){ savesettings(e["currenttarget"]["id"], e["currenttarget"]["checked"]); getsettings(e["currenttarget"]["id"]); }); $("#ospthree").click(function(e){ savesettings(e["currenttarget"]["id"], e["currenttarget"]["checked"]); getsettings(e["currenttarget"]["id"]); }); $("#ospfour").click(function(e){ savesettings(e["currenttarget"]["id"], e["currenttarget"]["checked"]); getsettings(e["currenttarget"]["id"]); });
settings functions:
function savesettings(aval, akey){ localstorage.setitem(aval, json.stringify(akey)) } function getsettings(akey){ var str = localstorage.getitem(akey); return json.parse(str); }
there couple of ways it. i've put them in order of best way of doing in opinion.
1. classes
apply class current elements (#ospone
- #ospfour
). example, .settingsbtn
.
html
<input type="checkbox" id="#ospone" class="settingsbtn" /> <input type="checkbox" id="#osptwo" class="settingsbtn" /> <input type="checkbox" id="#ospthree" class="settingsbtn" /> <input type="checkbox" id="#ospfour" class="settingsbtn" />
javascript
$('.settingsbtn').click(function(e) { savesettings(e.currenttarget.id, e.currenttarget.checked); getsettings(e.currenttarget.id); });
2. select checkboxes
assuming using checkboxes , on each 1 want update settings on click, can select checkboxes accordingly.
$('input[type=checkbox]').click(function(e) { savesettings(e.currenttarget.id, e.currenttarget.checked); getsettings(e.currenttarget.id); });
3. ^=
selector
you can select elements have id starts osp
.
$('[id^=osp]').click(function(e) { savesettings(e.currenttarget.id, e.currenttarget.checked); getsettings(e.currenttarget.id); });
4. single selector
combine selectors one.
$('#ospone, #osptwo, #ospthree, #ospfour').click(function(e) { savesettings(e.currenttarget.id, e.currenttarget.checked); getsettings(e.currenttarget.id); });
Comments
Post a Comment