如何在触发onclick事件的函数中使用相同的元素 [英] How to use the same element into a function which triggers the onclick event

查看:69
本文介绍了如何在触发onclick事件的函数中使用相同的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对外部文件中的脚本使用以下编码

I am using the following coding for the script in external file

function DiableLink(elem){
   console.log($(elem).attr('type'));
   if($(elem).hasClass('disabled')) {
       return false;
   }
   else {
       $(elem).addClass('disabled');
   }
}

在html中如下使用

<a onClick="DiableLink(this);" class="hid" href="somelink.jsp"></a>


我使用与ID相同的功能,如下所示:


I used the same function using ID as follow

$(function(){
   $('.hid').click(function(){
      var link = $(this);
      if(link.hasClass('disabled')) {
         return false;
      }
      else {
         link.addClass('disabled');
      }
  }); 
});

这是完美的工作(我是从stackoverflow获得的). 但是我不知道为什么在onclick事件中调用不起作用.任何人都可以帮忙吗?我在哪里错了

which is perfectly working (I got it from the stackoverflow). But i don't know why calling in onclick event doesn't work. Please can anyone help? where i got wrong

推荐答案

编辑:您的解决方案实际上与

EDIT: Your solution actually works with JS Bin

我写道:

我将在href内部调用该函数:

I'd call the function inside href:

<a href="javascript: yourFunction(); location.href='newpage.js';">Click</a>

但是如果您想通过href属性传递锚标记元素,那将是行不通的.因此,这将有效:

But it wouldn't work if you want to pass the anchor tag element through href attribute. So this will NOT work:

<a href="javascript: yourFunction(this); location.href='newpage.js';">Click</a>

在这种情况下,您必须使用onclick事件(如我之前编写的那样,是内联的或在单独的文件中).

In this case you have to use the onclick event (inline or in a separate file, as I wrote before).

这篇关于如何在触发onclick事件的函数中使用相同的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆