簡體   English   中英

將我的jQuery click事件與現有對象的onclick屬性混合在一起

[英]mixing my jQuery click events with existing object's onclick attribute

我正在使用jQuery但處理從JSF頁面生成的標記。 很多元素都有JSF代碼提供的onclick屬性(這不是我的領域)。

例:

<div onclick="[jsf js to submit form and go to next page]">submit</div>

我正在嘗試使用jQuery添加一些客戶端驗證。 我需要像這樣的偽代碼:

$('div').click(function(e){
  if(myValidation==true){
     // do nothing and let the JS in the onlick attribute do its thing
  } else {
     $error.show();
     // somehow stop the onclick attribute JS from firing
  }

})

是否有處理此問題的最佳做法?

我有一個想法是在頁面加載時,抓取onclick屬性的值,從對象中刪除onclick屬性,然后......好吧,那就是我迷路的地方。 我可以將JS作為文本緩存在數據屬性中,但是我不知道如何在以后解決這個問題。

如果需要,只需使用eval在jQuery click事件中運行onclick屬性代碼。 您需要刪除onclick屬性

<div onclick="alert('hi');">submit</div>

-

$(document).ready(function() {
    var divClick = $('#theDiv').attr('onclick');
    $('#theDiv').removeAttr('onclick');
});

$('#theDiv').bind('click', function(e) {
    if (myValidation == true) {
        // do nothing and let the JS in the onclick attribute do its thing
        eval(divClick);
    } else {
        $error.show();
        // somehow stop the onclick attribute JS from firing
        e.preventDefault();
    }
});

返回false或使用:

e.stopPropagation()

要么

e.preventDefault()

根據您的需要。

編輯

您可以保存原始活動:

var originalEvent = $('div').attr("onclick");
$('div').attr("onclick", false);

$('div').click(function(e) {
        if (false) {
            // do nothing and let the JS in the onlick attribute do its thing

            eval(originalEvent);
        }
        else {
            alert("error");
            // somehow stop the onclick attribute JS from firing
        }

    });

看看這個http://jsfiddle.net/j4jsU/

將if(false)更改為if(true)以查看表單有效時的hepens。

我喜歡e.stopProgation()和e.preventDefault(),但是如果你不喜歡這個策略,你也可以手動刪除onclick()屬性並手動調用成功驗證時使用的函數。

不同的筆畫..

你為什么不能這樣做:

div=document.getElementById('test');
oldClick=div.onclick;
bol=false;
div.onclick=function(){
    if(bol){
        oldClick();
    }
    else {
       alert('YOU SHALL NOT RUN INLINE JAVASCRIPT'); 
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM