jQuery / js-如何从基于href的类中获取菜单名称

我想在用户点击时获取菜单名称。

 Home   About  Contact 

因此,在此function中将弹出警报名称。

 function getMenu(){ //the code declare here alert('is click'); } 

预期结果首页点击/联系是点击

如果你想要一个jQuery方法….

您不需要onclick属性

this – 用于触发函数的元素

.textContent – 元素的文本内容

.trim() – 删除空格

 this.textContent.trim() 

元素>文本内容>修剪

 $('.menu').click(function(){ alert(this.textContent.trim()); }); 
   Home   About  Contact 

将点击的元素对象传递给函数:

  Home  

然后读取它的textContentinnerHTML属性:

 function getMenu(obj) { alert(obj.textContent); } 

您还可以修剪文本周围的空白区域:

 obj.textContent.trim(); 

查看下面的演示。

 function getMenu(obj) { alert(obj.textContent.trim()); } 
  Home   About  Contact 

像这样, this (指向当前元素)传递给您的函数getMenu ,并从您可以使用的链接获取内容.innerHTML 。

 function getMenu(el) { alert(el.innerHTML + ' is click'); } 
  Home   About  Contact 

在使用jQuery时使用更简洁的方法:

  Home   About  Contact  
 $(".menu").click(function(){ var currentId = $(this).attr("id"); alert($.trim($("#"+currentId).text())); }); 
   Home   About  Contact