在当前元素的onchange上发送$(this)
我有这个HTML
正如您所见,onchange调用getProducts函数。 我想知道是否有办法发送此类似的
我希望与当前的选择相关联
如果您尝试在函数中设置this
的值,可以使用.call
:
onchange="getProducts.call(this, 'standard_product');"
现在在你的getProducts函数中, this
将是接收事件的元素。
function getProducts( prod ) { alert( this ); // the
您还可以传递event
对象:
onchange="getProducts.call(this, 'standard_product', event);"
…并在你的函数中引用它:
function getProducts( prod, e ) { alert( this ); // the
编辑:正如@Cybernate所说 ,这是将DOM元素设置this
。 您需要将它包装在getProducts
函数$(this)
,或者getProducts
联处理程序中将其设置为。
虽然this
设置为元素本身更符合典型的事件处理程序行为。
编辑:为了进一步解释.call
作用,它允许您在正在调用的函数中手动设置它的值。
使用此function,只需提醒:
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
。 该函数没有改变,但是它的值是因为我们使用.call
手动设置它。
如果你有其他参数要发送,你只需将它们放在thisArg之后 。
function some_func( arg1 ) { alert( this ); alert( arg1 ); } some_func.call( 123, 456 );
this
警报将为123
,您发送的下一个参数将设置为arg1
参数,因此arg1
将为456
。
因此,您可以看到该call
基本上将您发送的第一个参数切掉,将其设置this
值,并将其余参数设置为与函数参数关联的正常参数。
你可以试试:
onchange="function(){var $this = $(this); getProducts('standard_product', $this)}"
为了更好地摆脱内联事件处理程序分配如下:
$(function(){ $(".category").click(function(){ var $this = $(this); getProducts('standard_product', $this); }); })