문제

I am currently working on a drop-down for changing the fonts on a site. Presently, there are a few different fonts available from the drop-down. The code that is called when one of the drop-down sections is clicked is as follows:

jQuery(function($) {
if ( localStorage.getItem('font-01') ) {
    $('#font-css-01').prop('disabled', localStorage.getItem('font-01') == 'true');
}

$('#font-selector-01').on('click', function() {
    $('#font-css-01').prop('disabled', function(_, prop) {
        localStorage.setItem('font-01', !prop);
        return !prop;
    });
});
});

Now, this script repeats for each font option (with only the ending numbers changed, obviously). However, I need the script to disable any previous font choices when enabling the new font choice; presently, unexpected behaviour can arise when a user selects a non-default font and then selects another non-default font (e.g., selects font-01, then selects font-02). In essence, I'm not sure how to go about expanding this script so it resets previous choices before applying new choices.

The .prop() function is targeting the stylesheet ids for the various fonts, and the drop-down's subitems are labelled consecutively #font-selector-01 through $font-selector-n.

도움이 되었습니까?

해결책

For link tags use data-fid instead of id:

<link data-fid='01' href='...' rel='...' disabled>
<link data-fid='02' href='...' rel='...' disabled>

As you can see, they should be disabled by default.
Add class font-selector-c and attribute data-fid='xx' to each li. Then the code:

$('.font-selector-c').on('click', function() {
    var fid = $(this).data('fid')
    $('link[data-fid]').prop('disabled', true) // disable all the stylesheets
    $('link[data-fid="' + fid + '"]')
        .prop('disabled', false) // enable one needed
    localStorage.setItem('font', fid) // save the id of the selected
});
$('#font-selector-reset').on('click', function() {
    $('link[data-id]').prop('disabled', true) // disable all the stylesheets
    localStorage.setItem('font', null) // remove saved id
});

// On start: recalling user's choice
var c_fid = localStorage.getItem('font')
if (c_fid)
    $('link[data-fid="' + c_fid + '"]').prop('disabled', false)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top