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? ?
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:
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.
If you want to call jq's method, you should use $(this) to represent the jq object