mixing my jQuery click events with existing object

2019-02-19 02:16发布

问题:

I'm using jQuery but dealing with markup produced from JSF pages. A lot of the elements have onclick attributes provided by the JSF code (which isn't my realm).

Example:

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

I'm trying to add some client side validation with jQuery. I need something like this pseudo code:

$('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
  }

})

Is there a best-practice for handling this?

One thought I had was that on page load, grab the onclick attribute's value, delete the onclick attribute from the object, then...well, that's where I get lost. I could cache the JS as text in a data- attribute, but I'm not sure how to fire that off later.

回答1:

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


回答2:

Either return false or use:

e.stopPropagation()

or

e.preventDefault()

Depending on your needs.



回答3:

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.



回答4:

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..



回答5:

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