jQuery 如何编辑“选择”标签中的“onchange”属性?(使用jQuery)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3637971/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:47:51  来源:igfitidea点击:

How to edit 'onchange' attribute in a 'select' tag? (using jquery)

jqueryhtmleventsselect

提问by vitorhsb

I'm trying to edit the 'onchange' event of an existent 'select' element.

我正在尝试编辑现有 'select' 元素的 'onchange' 事件。

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:

每当我尝试更改其“onchange”属性时,我都会使用以下内容:

$("#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?

仅供参考,这段应该没问题的代码不起作用,'onchange' 属性保持不变。那么应该如何编辑呢?

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?

但问题仍然存在,是否可以更改“onchange”属性而不首先将其删除?

回答by Justin Russell

Not an exact answer to the question, but I'd probably remove the event using this:

不是问题的确切答案,但我可能会使用以下方法删除事件:

document.getElementById('sel_id').onchange = undefined;

(as seen at How to Clear/Remove JavaScript Event Handler?)

(如如何清除/删除 JavaScript 事件处理程序?

and then go with this:

然后用这个:

$('#sel_id').change(function() { foo_2(); });

回答by user113716

Works for me if I use the native setAttribute().

如果我使用本机setAttribute().

Also, remember that you need quotes around the selector.

另外,请记住,选择器周围需要引号。

$("#sel_id")[0].setAttribute("onchange", "foo_2()");

Also remember to define foo_2in the global namespace, and not inside jQuery's .ready()function.

还要记住foo_2在全局命名空间中定义,而不是在 jQuery 的.ready()函数内部。

回答by jcubic

Use JQuery change function.

使用 JQuery 更改功能。

$('#sel_id').change(function() {
  //your code
});

回答by KeatsKelleher

Here's a way to do it using just javascript:

这是一种仅使用 javascript 即可完成的方法:

<html>
<head>
<script type = "text/javascript" langauge="JavaScript">
function foo (){
    alert("foo");
}
function fi() {
    alert('fi');
}
</script>
</head>
<body>
<select id = "select_list" onchange="foo();">
<option value = "1">1</option>
<option value = "2">2</option>
</select>
<input type = "button" value = "change" onclick = "document.getElementById('select_list').onchange = fi;">
</body>
</html>