我正在使用 jQuery,但要处理从 JSF 页面生成的标记。许多元素都具有 JSF 代码提供的 onclick 属性(这不是我的领域)。
例子:
<div onclick="[jsf js to submit form and go to next page]">submit</div>
我正在尝试使用 jQuery 添加一些客户端验证。我需要这样的伪代码:
$('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
}
})
是否有处理此问题的最佳实践?
我的想法是在页面加载时,获取 onclick 属性的值,从对象中删除 onclick 属性,然后......好吧,这就是我迷路的地方。我可以将 JS 作为文本缓存在数据属性中,但我不确定稍后如何触发它。
最佳答案
如果需要,只需使用 eval
在您的 jQuery 点击事件中运行 onclick 属性代码。您需要删除 onclick
属性
<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();
}
});
关于javascript - 将我的 jQuery 单击事件与现有对象的 onclick 属性混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7507861/