2

给定以下代码:

$(".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)

以及所有其他方式。

4

2 回答 2

1

您可以使用.currentTargetjQuery 事件对象作为第一个参数传递:

$(".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
        }
});
于 2012-07-01T19:36:20.097 回答
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
    //-----
});
于 2012-07-01T19:36:44.693 回答