如何编辑“onchange” “select”中的属性标签? (使用jquery)
我正在尝试编辑现有“select”元素的“onchange”事件。
例如,我有以下代码:
<select id="sel_id" onchange="javascript:foo();" >
每当我尝试更改其“onchange”属性时,我都会使用以下内容:
$("#sel_id").attr("onchange", "foo_2()");
仅供参考,这段应该没问题的代码不起作用,“onchange”属性保持不变。那么应该如何编辑呢?
修正:
您可以删除该属性,然后绑定不同的函数,例如:
$("#sel_id").removeAttr("onchange").bind("change", function(){ foo_2(); });
但问题仍然存在,是否可以更改“onchange”属性而不首先删除它?
I'm trying to edit the 'onchange' event of an existent 'select' element.
For example purposes I have the following code:
<select id="sel_id" onchange="javascript:foo();" >
and whenever I try to change its 'onchange' attribute I was using the following:
$("#sel_id").attr("onchange", "foo_2()");
FYI, this code which should be fine doesn't work, the 'onchange' attribute remains unchanged. So how should you edit it?
AMMENDMENT:
You can remove the attribute and then bind a different function like:
$("#sel_id").removeAttr("onchange").bind("change", function(){ foo_2(); });
but the issue remains, is it possible to change the 'onchange' attribute without removing it in the first place?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不是问题的确切答案,但我可能会使用以下方法删除事件:(
如 如何清除/删除 JavaScript 事件处理程序? )
,然后执行以下操作:
Not an exact answer to the question, but I'd probably remove the event using this:
(as seen at How to Clear/Remove JavaScript Event Handler? )
and then go with this:
如果我使用本机
setAttribute()
,则适用于我。另外,请记住您需要在选择器周围加上引号。
还要记住在全局命名空间中定义
foo_2
,而不是在 jQuery 的.ready()
函数内。Works for me if I use the native
setAttribute()
.Also, remember that you need quotes around the selector.
Also remember to define
foo_2
in the global namespace, and not inside jQuery's.ready()
function.使用JQuery更改功能。
Use JQuery change function.
这是一种仅使用 javascript 即可实现的方法:
Here's a way to do it using just javascript: