mixing my jQuery click events with existing object#39;s onclick attribute(将我的 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 属性混合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将我的 jQuery 点击事件与现有对象的 onclick 属性混


基础教程推荐
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01