Setting a cookie based on the name of the link that is clicked

后端 未结 4 574
一个人的身影
一个人的身影 2021-01-13 16:28

TLDR When clicking on a link I want to assign a cookie with a name of instrument and a value of the text on the link clicked.

Using Jquery.1.4.2.min

相关标签:
4条回答
  • 2021-01-13 16:36

    Try this:

    $('a[href="page.html"]').click(function(e)
    {
     // prevent default action
     e.preventDefault();
     var name = 'instrument';
     // get link text
     var value = $(this).text();
     // set cookie
     $.cookie(name, value, { expires: 365 });
     // now go to link's location
     document.location.href = $(this).attr('href');
    });
    
    0 讨论(0)
  • 2021-01-13 16:42

    Using the answer from Zack above I changed the element tag. The only issue is it will set the cookie for whichever link is followed wether it be for the link I want or not but it sets the cookie and works for where it is needed. IF there is a cleaner approach it would be appreciated.

    $(document).ready( function() {
        $('a[href="page.html"]').each( function() {
            // Kill the link's link feature.
            _href = $(this).attr('href');
            $(this).attr("rel", _href).attr("href", "javascript:void(0);");
        });
        $('a').click(function() {
            var name = 'instrument';
            var value = $(this).text();
            $.cookie(name, value, { expires: 365 });
            // Go places
            document.location.href = $(this).attr('rel');
        });
    });
    

    Massive thanks to Sarfraz and Zack for all the help at least I have something that works for now ^^

    0 讨论(0)
  • 2021-01-13 16:45

    This is hackish, but it works for me.

    $(document).ready( function() {
        $('a.cookier').each( function() {
            // Kill the link's link feature.
            _href = $(this).attr('href');
            $(this).attr("rel", _href).attr("href", "javascript:void(0);");
        });
        $('a.cookier').click(function() {
            var name = 'instrument';
            var value = $(this).text();
            $.cookie(name, value, { expires: 365 });
            // Go places
            document.location.href = $(this).attr('rel');
        });
    });
    

    My markup looks like this:

    <a class="cookier" href="hrrrngh.html">Shazam!</a>
    

    I use a similar method for "un-linking" my links on pages that use AJAX but must degrade gracefully.

    Note: You'll probably want to pick a classier class than "cookier."

    Edit:

    You could select those <a>'s in there with any of these, pick whichever doesn't select other stuff on the page.

    .dtree img + a
    .dTreeNode > a
    .dTreeNode a.node
    .dTreeNode a[onclick=|javascript].node
    
    0 讨论(0)
  • 2021-01-13 16:47
    var value = $(this);
    

    will assign the jQuery object to value. Use

    var value = $(this).text();
    

    or

    var value = $(this).attr('href');
    
    0 讨论(0)
提交回复
热议问题