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

查看:16
本文介绍了将我的 jQuery 点击事件与现有对象的 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- 属性中的文本,但我不确定以后如何触发它.

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 点击事件中运行 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 点击事件与现有对象的 onclick 属性混合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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