Mat*_*iby 5 html javascript jquery
我有这个HTML
<select class="category" style="margin-bottom: 5px;" onchange="getProducts('standard_product');">
Run Code Online (Sandbox Code Playgroud)
正如您所见,onchange调用getProducts函数.我想知道是否有办法发送此类似的
<select class="category" style="margin-bottom: 5px;" onchange="getProducts('standard_product', $(this));">
Run Code Online (Sandbox Code Playgroud)
我希望与当前的选择相关联
如果您尝试设置this函数的值,可以使用.call:
onchange="getProducts.call(this, 'standard_product');"
Run Code Online (Sandbox Code Playgroud)
现在在你的getProducts函数中,this将是接收事件的元素.
function getProducts( prod ) {
alert( this ); // the <select> element
}
Run Code Online (Sandbox Code Playgroud)
您还可以传递event对象:
onchange="getProducts.call(this, 'standard_product', event);"
Run Code Online (Sandbox Code Playgroud)
...并在您的函数中引用它:
function getProducts( prod, e ) {
alert( this ); // the <select> element
alert( e.type ); // the event type
}
Run Code Online (Sandbox Code Playgroud)
编辑:正如@Cybernate所说,这是将DOM元素设置为this.您需要将其包装在getProducts函数中$(this),或者在内联处理程序中将其设置为.
虽然设置this元素本身更符合典型的事件处理程序行为.
编辑:为了进一步说明是什么.call,它允许您手动设置this您正在调用的函数的值.
使用此功能,只需提醒this:
function some_func() {
alert( this );
}
Run Code Online (Sandbox Code Playgroud)
以基本方式(在浏览器中)调用它this可以引用DOM窗口.
some_func(); // the alert will be DOM Window
Run Code Online (Sandbox Code Playgroud)
但现在让我们调用.call,并将第一个参数设置为123.
some_func.call( 123 ); // the alert will be 123
Run Code Online (Sandbox Code Playgroud)
您现在可以看到警报显示123.函数没有改变,但是this因为我们已经手动设置了它的值.call.
如果你有其他参数要发送,你只需将它们放在thisArg之后.
function some_func( arg1 ) {
alert( this );
alert( arg1 );
}
some_func.call( 123, 456 );
Run Code Online (Sandbox Code Playgroud)
该this警报将是123,你发送下一个参数将被设置为arg1参数,所以arg1会456.
因此,您可以看到call基本上切掉您发送的第一个参数,将其设置为值this,并将其余参数设置为与函数参数关联的正常参数.