将我的jQuery click事件与现有对象的onclick属性混合在一起
我正在使用jQuery但处理从JSF页面生成的标记。 很多元素都有JSF代码提供的onclick属性(这不是我的领域)。
例:
submit
我正在尝试使用jQuery添加一些客户端validation。 我需要像这样的伪代码:
$('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 click事件中运行onclick属性代码。 您需要删除onclick
属性
submit
–
$(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(); } });
返回false或使用:
e.stopPropagation()
要么
e.preventDefault()
根据您的需要。
编辑
您可以保存原始活动:
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 } });
看看这个http://jsfiddle.net/j4jsU/
将if(false)更改为if(true)以查看表单有效时的hepens。
我喜欢e.stopProgation()和e.preventDefault(),但是如果你不喜欢这个策略,你也可以手动删除onclick()属性并手动调用成功validation时使用的函数。
不同的笔画..
你为什么不能这样做:
div=document.getElementById('test'); oldClick=div.onclick; bol=false; div.onclick=function(){ if(bol){ oldClick(); } else { alert('YOU SHALL NOT RUN INLINE JAVASCRIPT'); } }