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

淺唱寂寞╮ 提交于 2019-12-01 08:24:44
Mohsen

Just use eval to run onclick attribute code in your jQuery click event if you want it. You need to remove onclick attribute

<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();
    }
});

Either return false or use:

e.stopPropagation()

or

e.preventDefault()

Depending on your needs.

EDIT

You can save original event:

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
        }

    });

take a look at this http://jsfiddle.net/j4jsU/

Change if(false) to if(true) to see what hepens when form is valid.

I like e.stopProgation() and e.preventDefault(), but if you do not prefer that strategy, you could also manually remove the onclick() attribute and manually call the function it was using upon successful validation.

Different strokes..

Why can't you do something like:

div=document.getElementById('test');
oldClick=div.onclick;
bol=false;
div.onclick=function(){
    if(bol){
        oldClick();
    }
    else {
       alert('YOU SHALL NOT RUN INLINE JAVASCRIPT'); 
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!