获取最后点击的HTML书签

时间:2013-11-25 19:30:52

标签: javascript jquery html

是否可以通过javascript / jquery获取最后点击的html书签?

下面是html:

<a href="#div1">div1</a>
<a href="#div2">div2</a>

和DIV1如下:

<div id="div1">
    DIV 1 - Lorem ipsum dolor sit amet, solet nostrud concludaturque no eam. Ne quod recteque pri. Porro nulla zril mei eu. Eu nibh rebum pri, eu est maiorum menandri, ridens tamquam abhorreant te eum. Ipsum definiebas ad mel.</p><p>Lorem ipsum dolor sit amet, solet nostrud concludaturque no eam. Ne quod recteque pri. Porro nulla zril mei eu. Eu nibh rebum pri, eu est maiorum menandri, ridens tamquam abhorreant te eum. Ipsum definiebas ad mel.</p><p>Lorem ipsum dolor sit amet, solet nostrud concludaturque no eam. Ne quod recteque pri. Porro nulla zril mei eu. Eu nibh rebum pri, eu est maiorum menandri, ridens tamquam abhorreant te eum. Ipsum definiebas ad mel.
<div>

和DIV1如下:

<div id="div2">
    DIV 2 - Lorem ipsum dolor sit amet, solet nostrud concludaturque no eam. Ne quod recteque pri. Porro nulla zril mei eu. Eu nibh rebum pri, eu est maiorum menandri, ridens tamquam abhorreant te eum. Ipsum definiebas ad mel.</p><p>Lorem ipsum dolor sit amet, solet nostrud concludaturque no eam. Ne quod recteque pri. Porro nulla zril mei eu. Eu nibh rebum pri, eu est maiorum menandri, ridens tamquam abhorreant te eum. Ipsum definiebas ad mel.</p><p>Lorem ipsum dolor sit amet, solet nostrud concludaturque no eam. Ne quod recteque pri. Porro nulla zril mei eu. Eu nibh rebum pri, eu est maiorum menandri, ridens tamquam abhorreant te eum. Ipsum definiebas ad mel.
<div>

jsFiddle sample

我想有一个我可以调用的javascript函数,告诉我是否点击了书签,以及实际点击了哪个书签。

3 个答案:

答案 0 :(得分:0)

<强> JSFIDDLE DEMO

$('a').click(function () {
    alert("You clicked" + this.href); // Will give you the full link
});

<强> JSFIDDLE DEMO 2

alert("You clicked " + this.href.split('#')[1]); //Will give just the div id

答案 1 :(得分:0)

您需要在方法中找到某种标识符。我刚刚使用了您的链接的HTML内容:div1div2

JSFiddle

$("a").click(function(){
    alert("Clicked "+$(this).html()) 
});

有很多方法可以做到这一点。根据您要显示的内容,您始终可以设置链接的属性,然后使用jQuery查找该特定属性。

<a href="#div1" display="You clicked div 1!">Div 1</a>

$("a").click(function(){
    alert($(this).attr("display"));
});

答案 2 :(得分:0)

试试这个。

var bookmarkID;
$(document).ready(function(){
    $('a').click(function(){
    bookmarkID = $(this).attr('href').split('#')[1];
        console.log(bookmarkID);
    });
});

在这种情况下,您可以获取变量bookmarkID中的最后一个书签。

Fiddle