在 onClick 中使用 JQuery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1274430/
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
Using JQuery within onClick
提问by VoteyDisciple
Am I allowed to use JQuery within an onClick function?
我可以在 onClick 函数中使用 JQuery 吗?
For example:
例如:
<a onclick="my_save_function($("#inputID").val())">
<input type=hidden id="inputID" value="foo">
<a onclick="my_save_function($("#inputID").val())">
<input type=hidden id="inputID" value="foo">
Such that, when clicked, the anchor tag runs this:
这样,当点击时,锚标签运行:
my_save_function(foo);
my_save_function(foo);
After a few searches, I couldn't find a similar topic. Thank you for any help.
经过几次搜索,我找不到类似的主题。感谢您的任何帮助。
回答by VoteyDisciple
Sure. jQuery doesn't exist in any special universe; it's just a collection of JavaScript functions that you might find (extraordinarily) useful.
当然。jQuery 不存在于任何特殊的宇宙中;它只是您可能会发现(非常)有用的 JavaScript 函数的集合。
However, if you're using jQuery anyway, why not properly attach the onclick event from within jQuery? You'd just have to do:
但是,如果您无论如何都在使用 jQuery,为什么不在 jQuery 中正确附加 onclick 事件呢?你只需要这样做:
$(document).ready(function() {
$("#id-for-that-link").click(function() {
my_save_function($("#inputID").val());
});
});
回答by inkedmn
try this (you'll need an id on the anchor tag):
试试这个(你需要在锚标签上有一个 id):
<a onclick="my_save_function(this.id);">
and in your javascript:
并在您的 javascript 中:
function my_save_function(elid){
v = $("#"+elid).val();
// do stuff with v
}
回答by flatline
Honestly, you'd already written the code and markup, couldn't you just run it and see if it worked?
老实说,您已经编写了代码和标记,您就不能运行它看看它是否有效吗?
In answer to your question, yes, this should work fine, but watch your nested quotations. It would be better form and easier to read/maintain if you add a click handler to the element than embed the function body in the attribute string.
在回答您的问题时,是的,这应该可以正常工作,但请注意您的嵌套引用。如果将单击处理程序添加到元素中,而不是将函数体嵌入到属性字符串中,那将是更好的形式并且更易于阅读/维护。
回答by Michal - wereda-net
You can even put other jquery code like this:
您甚至可以像这样放置其他 jquery 代码:
onclick="$('#myid').closest('tr').hide();"