检测单击哪个锚点

时间:2014-04-16 14:54:08

标签: javascript html anchor

我有很多像这样的标签

<a href="javascript:changeFreq()">Anchor 1</a>
<a href="javascript:changeFreq()">Anchor 2</a>
<a href="javascript:changeFreq()">Anchor 3</a>

如何识别changeFreq功能中单击了哪个a。 我尝试使用this指针,但它引用了window个对象。 我无法在此上下文中使用onclick事件

有什么想法吗?

5 个答案:

答案 0 :(得分:3)

使用适当的事件处理程序 标记

<a href="#" class="anchor">Anchor 1</a>
<a href="#" class="anchor">Anchor 2</a>
<a href="#" class="anchor">Anchor 3</a>

var anchors = document.querySelectorAll('.anchor');

for (var i=0; i<anchors.length; i++) {
    anchors[i].addEventListener('click', handler, false);
}

function handler() {

    // now "this" is the element

}

FIDDLE

答案 1 :(得分:2)

如果您在this标记中使用onclick,则会将a代码引用传递到您的函数中。

http://jsfiddle.net/V3W38/ e.g。

<a href="#" onclick="return changeFreq(this)">Anchor 1</a>
<a href="#" onclick="return changeFreq(this)">Anchor 2</a>
<a href="#" onclick="return changeFreq(this)">Anchor 3</a>

<强>的Javascript

function changeFreq(element)
{
    // this is reference to the a tag you clicked on
    console.log(element.href);

    return false;
}

答案 2 :(得分:2)

这是一个只有一个事件监听器的解决方案。这个想法只附加一个监听器,然后根据点击的内容委派做什么。这样你就没有大量的听众来完成一个人可以处理的工作。有了这个问题,这可能有点过头了,但我确实想提供一个替代方案。

<强> jsFiddle

<强> HTML

<!--
Parent div to have the actual listener. 
Whenever an anchor is clicked, the event will bubble up to the #wrap div
-->
<div id="wrap">
   <!--Each div has a data-freq attribute to pass it's frequency-->
   <a id="a1" href="#" data-freq="1">Anchor 1</a><br>
   <a id="a2" href="#" data-freq="10">Anchor 2</a><br>
   <a id="a3" href="#" data-freq="100">Anchor 3</a><br>
</div>
<!--Print out the frequency-->
<div>Frequency: </div>
<div id="freq">0</div>

<强> JS

// Get the important elements
var wrap = document.getElementById("wrap"),
        freqDiv = document.getElementById("freq");

// Function to let us change frequency
function changeFrequency(amount) {
   freqDiv.innerHTML = amount;
}

// Add only one event listener and let clicks bubble up
wrap.addEventListener("click", function(e) {
   // Change the frequency by the data-freq value
   changeFrequency(e.target.dataset["freq"]);
   // Don't change pages
   e.preventDefault();
});

答案 3 :(得分:0)

您是否只是尝试在函数中添加输入变量?

<a href="javascript:changeFreq(1)">Anchor 1</a>
<a href="javascript:changeFreq(2)">Anchor 2</a>
<a href="javascript:changeFreq(3)">Anchor 3</a>

JS:

function changeFreq(anchorId){
     switch(anchorId){
         case 1:
         ///...
         break;
         //...
     }
}

答案 4 :(得分:0)

enter link description here

如果单击一个锚标记,则会返回锚标记href或id,并在警报中显示您可以根据需要使用

Jquery的

$( "a" ).click( handler ).find( "a" );
function handler( event ) {
  var target = $( event.target );

  if ( target.is( "a" ) ) {
    alert(target.html());
        alert(target.attr("href"));
      alert(target.attr("id"));
  }
}

CSS

<a href="javascript:changeFreq(this)">Anchor 1</a>
<a href="javascript:changeFreq(this)">Anchor 2</a>
<a id="i1" href="javascript:changeFreq(this)">Anchor 3</a>