我有这个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)
中,或者在内联处理程序中将其设置为这样。
尽管将 this
设置为元素本身更符合典型的事件处理程序行为。
编辑:为了进一步解释.call
的作用,它允许您手动设置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 );
this
警报将为 123
,您发送的下一个参数将设置为 arg1
参数,因此 arg1
将是 456
。
所以你可以看到 call
基本上切掉了你发送的第一个参数,将它设置为 this
的值,并将剩余的参数设置为你的普通参数关联使用您的函数参数。
关于javascript - 在当前元素的 onchange 上发送 $(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6335399/