如何让input元素触发jQuery自动完成小部件?
我有几个使用jQuery自动完成function增强的输入字段。 触发选择事件时如何获取相应的输入字段?
$('input[type=text]').autocomplete({ source: 'suggestions.php', select: function(event, ui) { // here I need the input element that have triggered the event } });
尝试使用$(this)
$('input[type=text]').autocomplete({ source: 'suggestions.php', select: function(event, ui) { // here I need the input element that have triggered the event alert($(this).attr('name')); } });
我正在为source
参数使用匿名函数,并且其中的$(this)
引用了函数,而不是触发它的元素。 我不得不使用$(this.element)
。
最终的代码与此类似(我将其简化为演示目的) :
$( ".regionsAutocomplete" ).autocomplete({ source: function(request, response){ //The next line is the important one for this example var input = this.element; $(input).css('color','red'); var data = {'foo':'bar'}; $.ajax({ 'url': ajaxurl, 'data': data, 'method': "POST", 'dataType': "json", 'success': function(data) { response(data); } }); } });
您可以使用$(this)
或event.target
。
然后,您可以使用$(this).prop('name')
或event.target.name
$(this).prop('name')
。
演示
据我所知,这个例子你不需要$()
。 this
可以正常工作,因为name是一个已定义的属性。
this.name
使用$(this)
select: function(event, ui) { $(this).attr('name'); }