如果您尝试设置的值this
在你的函数中,你可以使用.call
:
onchange="getProducts.call(this, 'standard_product');"
现在在您的 getProducts 函数中,this
将是接收事件的元素。
function getProducts( prod ) {
alert( this ); // the <select> element
}
您还可以通过event
object:
onchange="getProducts.call(this, 'standard_product', event);"
...并在您的函数中引用它:
function getProducts( prod, e ) {
alert( this ); // the <select> element
alert( e.type ); // the event type
}
EDIT:正如所指出的@Cybernate https://stackoverflow.com/users/527185/cybernate,这将 DOM 元素设置为this
。你需要把它包裹在你的getProducts
功能$(this)
,或者在您的内联处理程序中将其设置为这样。
虽然设定this
元素本身更符合典型的事件处理程序行为。
EDIT:为了进一步解释什么.call
是的,它可以让你manually设置值this
在您正在调用的函数中。
采取这个功能,它只是提醒this
:
function some_func() {
alert( this );
}
以基本方式(在浏览器中)调用它使得this
引用 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 );
The this
警报将是123
,并且您发送的下一个参数将被设置为arg1
参数,所以arg1
将456
.
所以你可以看到call
基本上切掉你发送的第一个参数,将其设置为this
,并将其余参数设置为与函数参数关联的普通参数。