[英]How to stop javascript onclick event
我有使用javascript onclick事件渲染圖像的外部鏈接。
我需要停止此點擊事件。該怎么辦?
例如:
Html is render by external script:
<div class="demo-link">
<img alt="" onclick="verifylock();" src="https://example.com" style="cursor:pointer;cursor:hand">
</div>
我已經嘗試過用jQuery,但沒有任何運氣:
$(".demo-link > img").click(function(e){
e.preventDefault();
});
您總是可以從onClick事件處理程序中返回false,可以調用preventDefault,stopImmediatePropagation或其他方法,但是由於在jQuery onclick之前調用了HTMLs onclick,因此在這里將無用。 如果您不想簡單地從HTML中刪除“ onclick”,則可以通過編程方式進行更改(甚至可以將其與jquery data()方法一起存儲,以備將來使用)。
$(".demo-link > img").each(function(e) {
$(this).onclick = function() { // overriding the onclick
return false;
}
});
下面的工作片段:
function defaultOnClick() { alert('Default event handler invoked!'); } $('.clickable').each(function() { $(this).data('onClickBackup', this.onclick); this.onclick = function(event) { alert('Overriden onclick'); return false; // if you need to ever call the original onclick, then call below // $(this).data('onClickBackup').call(this, event || window.event); }; });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <div class="clickable" onclick="defaultOnClick()">Click me!</div>
$(".demo-link > img").click(function(e){
return false;
});
您在單擊時編寫事件,並在img標簽中使用onclick調用函數。 因此,從img標簽中刪除onclick。
<img alt="" src="https://example.com" style="cursor:pointer;cursor:hand">
如果要調用函數verifylock(),請從處理程序中調用該函數以進行單擊
嘗試使用自己的代碼,並return false;
<img alt="" onclick="verifylock(); return false;" src="https://example.com" style="cursor:pointer;cursor:hand">
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.