点击链接的文字

 

在我的script.js中:

 var myFunc = function () { // I want to get the Text of the link eg if the first list item link is // clicked, store "Accept" in a variable. }; 

我怎样才能做到这一点?

您可以将当前链接作为参数传递给函数:

  

然后使用innerHTML属性获取里面的文本:

 var myFunc = function (link) { alert(link.innerHTML); }; 

更新:

我没注意到你的问题实际上是用jQuery标记的。 在这种情况下,我建议您不引人注意地订阅点击处理程序:

  

并在一个单独的js文件中:

 $(function() { $('.Buttons a').click(function() { alert($(this).text()); return false; }); }); 

更新2:

有人询问如果动态生成这些锚点,如何分配这些点击处理程序。 因此,我们假设您从以下标记开始:

 

    然后当某些事件发生时(点击或其他)你动态添加一个锚:

     $('
  • ', { html: $('', { href: '#', text: 'some text ....', click: myFunc }) }).appendTo('.Buttons');

    你在哪里定义了myFunc

     var myFunc = function() { alert($(this).text()); return false; } 

    既然你似乎在使用jQuery ……

     $("ul.buttons > li > a").click(function () { alert( $(this).text() ); myFunc(this); return false; }); 

    删除那些onclick处理程序。 ;)

      $('.Buttons li a').click(function(event) { var myVariable = $(this).text(); alert(myVariable); event.preventDefault(); }); 

    如果您正在使用jQuery,那么您可以绑定到这样的元素:

     //wait for document.ready to fire $(function () { //find the links in the `.Button` list and bind a click event handler to them $('.Buttons').find('a').on('click', function () { //alert the text of the clicked element alert($(this).text()); //prevent the normal behavior of the link, also stop the propagation of the event so no other elements fire event handlers for this event return false; }); }); 

    请注意.on()是jQuery 1.7中的新增内容,在这种情况下与使用.bind()相同: http : //api.jquery.com/on

    然后你的HTML里面不需要任何JS:

      

    $(this).text()应该适合你。

     $(function(){ $('.Buttons').click(function(){ alert($(this).html(); }) })