![](/img/trans.png)
[英]How to pass the id of an element that triggers an `onclick` event to the event handling function
[英]How to use the same element into a function which triggers the onclick event
我對外部文件中的腳本使用以下編碼
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相同的功能,如下所示
$(function(){
$('.hid').click(function(){
var link = $(this);
if(link.hasClass('disabled')) {
return false;
}
else {
link.addClass('disabled');
}
});
});
這是完美的工作(我是從stackoverflow獲得的)。 但我不知道為什么在onclick事件中調用不起作用。 有人可以幫忙嗎? 我錯了
如果您使用事件處理程序而非函數,則需要將onclick=""
屬性保留為空。
編輯 :您的解決方案實際上與JS Bin一起使用
我寫:
我會在href內部調用該函數:
<a href="javascript: yourFunction(); location.href='newpage.js';">Click</a>
但是,如果您想通過href屬性傳遞錨標記元素,那將是行不通的。 所以,這是不行的:
<a href="javascript: yourFunction(this); location.href='newpage.js';">Click</a>
在這種情況下,您必須使用onclick事件(內聯或在單獨的文件中,如我之前所寫)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.