开发者

Jquery : Replace All link depending cookie value and replace the true link after the click

开发者 https://www.devze.com 2023-02-21 20:01 出处:网络
I have a cookie value : clickotV I have multiple href with the same class \"t\" : <a href=\"link1.html\" class=\"t\">link1</a>

I have a cookie value : clickotV

I have multiple href with the same class "t" :

  • <a href="link1.html" class="t">link1</a>
  • <a href="link2.html" class="t">link2</a>
  • <a href="link2.html" class="t"><img src="image2.jpg" /></a>

When cookie value is 1 :

  • I must replace all href with the class "t" by out.php and add target _blank So i do this :

    $(document).ready(function(){
        if($.cookie('click开发者_C百科otV')==1){
            $("a.t").attr("href", "/out.php");
            $("a.t").attr("target", "_blank");
        }
    });
  • But I must replace the link origin (without _blank) after user click on a replaced link (out.php)

How do I ?


If you need to remember data, then you will have to store it, fortunately, jQuery has the .data() command for this purpose.

The major problem you will have is getting the href to change after a click. You could either bind the click event, set a short timeout to change the value back and unbind the click event after the default action. Or try and open the page in javascript, but that is often blocked.

Edit: Altered to reset all links on first click.

$(document).ready(function() {
    if ($.cookie('clickotV') == 1) {
        $('a.t').each(function() {
            var self = $(this);
            self.data('old-href', self.attr('href'))
                .attr({ 'href': '/out.php',
                        'target': '_blank' });

            // Timeout - option 1
            self.click(function() {
                setTimeout(function() {
                    $('a.t').each(function() {
                        $(this).attr('href', $(this).data('old-href')).unbind('click');
                    });
                }, 10);

                // passthrough for default action
                return true;
            });

            // JS new-window - option 2
            self.click(function() {
                var newWindow = window.open(self.attr('href'), '_blank');

                $('a.t').each(function() {
                    $(this).attr('href', $(this).data('old-href')).unbind('click');
                });

                newWindow.focus();
                return false;
            });
        });
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号