将我的jQuery click事件与现有对象的onclick属性混合 [英] mixing my jQuery click events with existing object's onclick attribute

查看:109
本文介绍了将我的jQuery click事件与现有对象的onclick属性混合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是jQuery,但处理的是从JSF页面生成的标记.许多元素具有JSF代码提供的onclick属性(这不是我的领域).

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

示例:

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

我正在尝试使用jQuery添加一些客户端验证.我需要类似下面的伪代码:

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?

我曾经想到的是,在页面加载时,抓住onclick属性的值,从对象中删除onclick属性,然后...嗯,这就是我迷路的地方.我可以将JS作为文本缓存在data-attribute属性中,但是我不确定如何稍后将其触发.

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.

推荐答案

如果需要,只需使用 eval 在jQuery click事件中运行onclick属性代码.您需要删除onclick属性

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

这篇关于将我的jQuery click事件与现有对象的onclick属性混合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆