javascript - 'this' 是否引用调用此函数的元素?

标签 javascript jquery jquery-ui reference this

在下面的代码片段中,我使用 $(this) 来引用调用该函数的元素。我知道这是不正确的,因为我打印了这些值,它给了我“未定义”。如何引用输入元素?

$(function() {
    $( ".datepicker" ).datepicker({
        onSelect: function (date, obj){
                if(confirm('Is this correct?: '+ date )) {
                    $.post('edit.php', {
                        "row": $(this).data('id'),
                        "date":date,
                        "field":$(this).name,
                        "ajax":'true'
                        });
                    }
                }
    });
});

这是 html 元素:

<input 
name="appvAcadVp" 
data-id="someid"  
class="datepicker" size="10" 
type="text"
placeholder="someholder"
>

最佳答案

jQuery 设置 this 本身,通常指向当前元素。

否则,在 JavaScript 中...

作为分配给属性的函数

var a = {
   b: function() {
      // `this` is `a`
   }
}

a.b();

异常(exception),属性被分配给变量。观察...

var c = a.b;
c(); // the `this` will point to `window`
<小时/>

作为分配给变量的函数

var a = function() {
   // `this` is `window`
}

a();
<小时/>

作为构造函数

var C = function() {
   // `this` is `c`
}

var c = new C();

请注意,如果您忘记使用 new 进行实例化,JavaScript 会将这些属性分配给全局对象(浏览器中的window)。

<小时/>

在全局范围内

// In global scope `this` is `window`
var d = this;
<小时/>

通过 call()apply()

调用

您还可以使用 call()apply() 函数方法显式设置 this

<小时/>

现在,解决你的问题...

Thanks for the explanation of 'this' but I still dont understand why the reference isn't working in my code

抱歉。

$(this).name 不起作用,因为 this 现在是一个 jQuery 对象,并且只有几个属性(其中没有一个是 name)。

使用 $(this).attr('name') 或将 this 与 jQuery 对象包裹起来,然后访问 this.name.

关于javascript - 'this' 是否引用调用此函数的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5826467/

相关文章:

Jquery 可拖动 + 置于最前面

css - 从 jQuery UI 对话框中删除特定样式

javascript - 动态重组 HTML 表格

jQuery - 在 Unslider 的每个 <li> 上运行函数

javascript - 如何仅在平板电脑/手机上将主 slider 的布局从 'partialview' 更改为 'fillwidth'

javascript - 这段代码是否将类属性添加到 foo 数组中?

jquery 选项卡在顶部添加空间

javascript - 捆绑后相对 templateUrls 的 Angular $templateCache 404 错误

javascript - 如何使用 PHP 和 Javascript 实现服务器推送/长轮询/comet

javascript - jQuery Toggle Navigation Bar 使用 Div