如何解决在当前元素的onchange上发送$this
|| 我有这个HTML<select class=\"category\" style=\"margin-bottom: 5px;\" onchange=\"getProducts(\'standard_product\');\">
如您所见,onchange调用了getProducts函数。我想知道是否有办法像这样发送
<select class=\"category\" style=\"margin-bottom: 5px;\" onchange=\"getProducts(\'standard_product\',$(this));\">
我希望它将与当前选择相关联
解决方法
如果要在函数中设置
this
的值,则可以使用.call
:
onchange=\"getProducts.call(this,\'standard_product\');\"
现在,在您的getProducts函数中,this
将成为接收事件的元素。
function getProducts( prod ) {
alert( this ); // the <select> element
}
您还可以传递event
对象:
onchange=\"getProducts.call(this,\'standard_product\',event);\"
...并在您的函数中引用它:
function getProducts( prod,e ) {
alert( this ); // the <select> element
alert( e.type ); // the event type
}
编辑:如@Cybernate所指出,这会将DOM元素设置为this
。您需要将其包装在getProducts
函数$(this)
中,或在内联处理程序中进行设置。
虽然将元素本身设置为2更加符合典型的事件处理程序行为。
编辑:为了进一步解释.call
的作用,它允许您在调用的函数中手动设置this
的值。
使用此功能,它仅会警告this
:
function some_func() {
alert( this );
}
以基本方式(在浏览器中)调用它使“ 2”引用DOM窗口。
some_func(); // the alert will be DOM Window
但是现在让我们使用.call
进行调用,并将第一个参数设置为123
。
some_func.call( 123 ); // the alert will be 123
您现在可以看到警报显示123
。该函数未更改,但是this
的值已更改,因为我们已使用.call
进行了手动设置。
如果您要发送其他参数,只需将其放在thisArg之后。
function some_func( arg1 ) {
alert( this );
alert( arg1 );
}
some_func.call( 123,456 );
“ 2”警报将是“ 21”,并且您发送的下一个参数将设置为“ 29”参数,因此,“ 29”将是“ 31”。
因此,您可以看到call
基本上会分割掉您发送的第一个参数,将其设置为this
的值,并将其余参数设置为与函数参数关联的普通参数。
, 你可以试试:
onchange=\"function(){var $this = $(this); getProducts(\'standard_product\',$this)}\"
为了更好地摆脱内联事件处理程序分配,如下所示:
$(function(){
$(\".category\").click(function(){
var $this = $(this);
getProducts(\'standard_product\',$this);
});
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。