开发者

jquery, grab the link href attribute that was last clicked: making a "follow to external link or don't follow"

I'm making a tiny script that adds a class of开发者_JAVA技巧 "external" to all external links, then when someone click an external link, it shows a div.question-wrapper that has a div.follow and a div.dontfollow in it, it also displays the url of the link you clicked in the div.question-wrapper. the only problem i'm having is copying the href attr of the link clicked to the button div.follow.

jquery:

$(".external").click(function() {
    thisurl = $(this).attr('href')
    $("#question-wrapper").fadeIn('normal')
    $("#follow").attr('href', "($(this).attr('href'))")
        return false;   
    $("#dontfollow").click(function() {
        $("#question-wrapper").fadeOut('normal')
    })
    $("#question-wrapper span").html(
        $(this).attr('href'))
        return false;
    }) 

html:

<div id="question-wrapper">
    Would you like to continue on to 
    <span id="url">space where link is</span>?
    <div id="follow">CONTINUE</div>
    <div id="dontfollow">STAY HERE</div>
</div>


You have the right idea, but divs cannot have hrefs, so I would use two a tags in the #question-wrapper making your HTML look like:

<div id="question-wrapper">
    Would you like to continue on to 
    <span id="url">space where link is</span><br/>
    <a id="follow">CONTINUE</a><br/>
    <a id="dontfollow" href="#">STAY HERE</a>
</div>

Also, if you put the href in quotes then it'll display literally, so

$("#follow").attr('href', "($(this).attr('href'))");

Will make the #follow if it is an A look like:

<a href="($(this).attr('href'))">blah</a>

Also, you already created thisurl so use it. Also use var, since without declaring them variables become global (properties of window):

$("#follow").attr('href', thiurl);

So the entire thing would look like:

$(function() {                                            // <== DOC ready

    $("#question-wrapper").hide();                        // Hide the QR to begin

    $("a.external").click(function() {    // Click handler for all external links

        var thisurl = $(this).attr('href'),                            // The url
            $qr = $("#question-wrapper");                               // The QR

        $qr.fadeIn('normal');                                      // Show the QR

        $("#follow").attr('href', thisurl);              // Set the URL of FOLLOW

          // Make #url a working link too
        $("#url").html('<a href="' + thisurl + '">' + thisurl + '</a>');

        $("#dontfollow").click(function() {
            $qr.fadeOut('normal');
            return false;
        });

        return false;
    });
});​

Try it out with this jsFiddle

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜