jQuery 使用复选框的“onclick”时防止默认操作的简单方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15554640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Easy way to prevent default action when using "onclick" of a checkbox?
提问by Roeland
This is my current solution:
这是我目前的解决方案:
html
html
<input type="checkbox" value="1" onclick="return do_stuff();" />
<input type="checkbox" value="1" onclick="return do_stuff2();" />
javscript:
脚本:
function do_stuff() {
return false;
}
function do_stuff2() {
return true;
}
I would like to avoid needing the "return" in the onclick call (ex. onclick="do_this();"
instead of onclick="return do_this();"
). I thought about using the preventDefault() function that jquery provides, but cant seem to get that working. Also, I dont want to bind "click" event if possible. I prefer using the "onclick". (easier to work with ajax loaded content)
我想避免在 onclick 调用中需要“返回”(例如,onclick="do_this();"
而不是onclick="return do_this();"
)。我想过使用 jquery 提供的 preventDefault() 函数,但似乎无法正常工作。另外,如果可能,我不想绑定“单击”事件。我更喜欢使用“onclick”。(更容易处理 ajax 加载的内容)
Thoughts?
想法?
回答by Radiotrib
The return value of an event handler determines whether or not the default browser behaviour should take place as well.
事件处理程序的返回值决定了是否也应该发生默认浏览器行为。
So ...
所以 ...
onclick='function(); return false;'
should fix it ...
应该修复它...
回答by Radiotrib
Have you tried calling the event.stopPropagation() method inside do_stuff() ... you'll need to pass in the event of course.
您是否尝试过在 do_stuff() 中调用 event.stopPropagation() 方法……当然,您需要传入事件。
onclick = 'do_stuff(event)'
function do_stuff(ev) {
if(ev.stopPropagation) {
// for proper browsers ...
ev.stopPropagation();
} else {
// internet exploder uses cancelBubble ...
window.event.cancelBubble = true;
}
// --- do some more stuff ---//
}