javascript onclick 调用 jQuery 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7415948/
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
onclick call jQuery function
提问by Jeffz
I have form with actively populated elements, something like:
我的表单包含活跃的元素,例如:
<input id="id1" type="button" name="some_name">
<input id="id2" type="button" name="another_name">
etc.
等等。
My options are limited here.
我的选择在这里是有限的。
I do not know id, as it is assigned by system dynamically (see: 1,2 next to id), so I cannot call JQ function by #. Order of elements change, they are shown in different sets etc.
我不知道 id,因为它是由系统动态分配的(参见:id 旁边的 1,2),所以我不能通过 # 调用 JQ 函数。元素的顺序发生变化,它们显示在不同的集合中等。
Class manipulation is not practical. Same goes for any other attrib - pretty much - some are used, some may be used - again - dynamically, so I do not want to mess with it.
类操作不实用。任何其他属性也是如此 - 几乎 - 有些被使用,有些可能会被使用 - 再次 - 动态,所以我不想弄乱它。
I can attach a js event thou (during form generation), e.g. onClick to particular, desired item.
我可以附加一个 js 事件(在表单生成期间),例如 onClick 到特定的、所需的项目。
<input id="id1" onClick="myFunc()" type="button" name="some_name">
<input id="id2" type="button" name="another_name">
I would not need to know id, class or anything in standard JS, since if element with myFunc is clicked, function is fired.
我不需要知道 id、class 或标准 JS 中的任何内容,因为如果单击带有 myFunc 的元素,则会触发函数。
Is it possible to accomplish something similar with JQ?
是否有可能用 JQ 完成类似的事情?
回答by Jamie Dixon
Since you can attach your onlick event inline, why not add a class at that point instead?
既然您可以内联附加您的 onlick 事件,那么为什么不添加一个类呢?
Adding a class to your input will allow you to hook into it easily with jQuery.
将一个类添加到您的输入将允许您使用 jQuery 轻松地连接到它。
<input class="myClass" [...] >
$('.myClass').click(function(){ [...] });
Update
更新
To directly answer the question you seem to be asking, no, jQuery doesn't have a unique way of firing events inline by using the HTML binding attributes.
要直接回答您似乎在问的问题,不,jQuery 没有使用 HTML 绑定属性内联触发事件的独特方式。
However, any function you create in Javascript can be fired inline. I do not recomend this approach since it's outdated and violates the seperation of concerns.
但是,您在 Javascript 中创建的任何函数都可以内联触发。我不推荐这种方法,因为它已经过时并且违反了关注点的分离。
回答by Joel A. Villarreal Bertoldi
I fail to see why you wouldn't use attributes as a reference. You could do:
我不明白你为什么不使用属性作为参考。你可以这样做:
$("input[type=button][name=some_name]")
Or a generic handler:
或通用处理程序:
$("input[type=button]").click(genericEventHandler);
function genericEventHandler()
{
var clickedButton = $(this);
/* ... */
}