给出以下代码:
$(".force-selection").blur(function() {
var value = $('matched-item').val();
//check if the input's value matches the selected item
if(value != $('#matched-item').data('selected-item')) {
//they don't, the user must have typed something else
$('#matched-item')
.val('') //clear the input's text
.data('selected-item', ''); //clear the selected item
}
});
如何引用与$(“。force-selection”)jQuery选择器匹配的元素?我对匿名JS函数不是很清楚,而且我很困惑人们如何知道有时会像这样声明它们:
function()
有时也喜欢这样:
function(event)
有时也喜欢这样:
function(element, update, options)
以及所有其他方式。
答案 0 :(得分:1)
您可以将使用jQuery事件对象传递的.currentTarget
作为第一个参数:
$(".force-selection").blur(function(e) { //<-- define e as parameter for this function. it's short for "event"
e.currentTarget; //The element a blur was triggered on
var value = $('#matched-item').val(); //<-- add "#"
//check if the input's value matches the selected item
if(value != $('#matched-item').data('selected-item')) {
//they don't, the user must have typed something else
$('#matched-item')
.val('') //clear the input's text
.data('selected-item', ''); //clear the selected item
}
});
答案 1 :(得分:0)
使用this关键字,它指的是当前的闭包。将它包装在jQuery调用中,它将变成引用的元素。
$(".force-selection").blur(function() {
var value = $('matched-item').val();
//check if the input's value matches the selected item
if(value != $('#matched-item').data('selected-item')) {
//they don't, the user must have typed something else
$('#matched-item')
.val('') //clear the input's text
.data('selected-item', ''); //clear the selected item
}
//-----
$(this) == current .force-selection
//-----
});