jquery - 这个 jquery 函数中的 this 等于什么?

标签 jquery

function populateTable() {

    // Empty content string
    var tableContent = '';

    // jQuery AJAX call for JSON
    $.getJSON( '/users/userlist', function( data ) {

      // Stick our user data array into a userlist variable in the global object
      userListData = data;

        // For each item in our JSON, add a table row and cells to the content string
        $.each(data, function(){
            tableContent += '<tr>';
            tableContent += '<td><a href="#" class="linkshowuser" rel="' + this.username + '">' + this.username + '</a></td>';
            tableContent += '<td>' + this.email + '</td>';
            tableContent += '<td><a href="#" class="linkdeleteuser" rel="' + this._id + '">delete</a></td>';
            tableContent += '</tr>';
        });

        // Inject the whole content string into our existing HTML table
        $('#userList table tbody').html(tableContent);
    });
};

有问题的代码位于字符串连接部分内。 rel= 部分中的 this.username 等于什么?我们如何在 jquery 中对其进行字符串插值?

这似乎是指数据。这是正确的吗?

这些文档中没有很好地解释,因为 $.each 这里接受两个参数......数据和回调。

https://api.jquery.com/each/

最佳答案

是的,因为data是对象数组this指向该数组内的单个对象。

您还可以通过回调函数中的显式参数访问当前对象:

$.each(data, function(index, obj) {
    console.log(this === obj);
});

关于jquery - 这个 jquery 函数中的 this 等于什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31036498/

相关文章:

jquery - 弹出图片的最简单方式,例如图片库组合、灯箱

javascript - html代码中div标签的错误消息

javascript - 在 Twitter 上显示和隐藏内容

javascript - 在 td 单击时更改按钮值

javascript - $(document).ready() 立即触发 window.open() 上下文

javascript - jQuery Cycle 插件在 IE6 中用背景图片中断

javascript - 如何重复循环遍历div

jquery - Jquery Nivo Slider 转换如何工作?

javascript - aria 隐藏属性不适用于后代

javascript - 单击更改事件菜单项的字体