javascript - this pointing problem in jquery event binding
習慣沉默
習慣沉默 2017-06-26 10:57:25
0
4
794

code show as below:


$(function(){
                $.ajax({
                    type:"GET",
                    url:"/msg",
                    success:function(data){
                        var html="";
                        for(var o of data){
                            html+=`
                                <tr>
                                    <td>${o.mid}</td>
                                    <td>${o.uname}</td>
                                    <td>${o.content}</td>
                                    <td>${o.pubtime}</td>
                                    <td>
                                        <a class="btn-del" href="${o.mid}">删除</a>
                                    </th>
                                </tr>
                            `;
                        }
                        $("#tb1").html(html);
                    }
                });

                $("#tb1").on("click","a.btn-del",(e)=>{
                    e.preventDefault();
                    //var mid=this.getAttribute("href");
                    console.log(this);
                });
            });

I need to bind the deletion event to a.btn-del generated by the asynchronous request, and I need to get the herf attribute value of the currently clicked element; it can be obtained through e.target; but it cannot be obtained through this. After console.log(this), output #document.

Isn’t this in the event proxy pointing to the currently clicked element? ?

習慣沉默
習慣沉默

reply all(4)
巴扎黑

Change (e)=> {} to function(e){} and have a look.

You should first understand the binding mechanism of this.

This in arrow functions points to the outer function scope.

曾经蜡笔没有小新

The following are several ways to call js functions:

var func = function(a,b){
    console.log(this); 
    console.log(a + ' ' + b)
};

var self = 'test';
func(1,2);   // this 是 window 对象, 因为此时调用函数的是window对象
func.call(self,1,2);  // this是 字符串  'test'
func.apply(self,[1,2]); // this是 字符串  'test'

JS is not an object-oriented language. Compared with Java, the syntax of object-oriented implementation is a bit strange.
If the function is called as func(), the value of this depends on the object in which the function is called.
When setting the callback function, if the this parameter is not passed, it is the calling method of func(). The general writing method should be to use another variable to save the value of this, usually the variable name is self.

var self = this;
XXXX.callback = function(){
    console.log(self);
};
给我你的怀抱

If you want to call jq's method, you should use $(this) to represent the jq object

扔个三星炸死你
获取href :

 this.hash 
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!