替换JavaScript上下文

时间:2018-12-03 15:29:02

标签: javascript jquery

我阅读了一些有关范围和上下文的文章,但是我仍然有一个问题,here是我的JSFiddle。我想将功能更改为箭头功能,并用其实际窗口值替换“ this”关键字。

这是我当前的代码。

User.Identity

这是我尝试过的方法,但似乎不起作用。

$(this).on('click', "i.fa.fa-minus-square", function(e) {
  table.row( $(this).closest('tr') ).remove().draw();
});

任何想法都将不胜感激。

2 个答案:

答案 0 :(得分:1)

在事件处理程序中,将@GET @Path("react-client/{path: .*\\..+$}") public Response serveReactClientContent(@Context HttpServletRequest httpServletRequest) { final String pathToResource = httpServletRequest.getRequestURI(); Pattern p = Pattern.compile("/react-client/(.+?(?=static/|favicon.ico))", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(pathToResource); String resolveResourcePath = m.replaceAll("/react-client/"); return serveStaticContent(resolveResourcePath); } 替换为this(这是触发事件的元素,与e.target相同):

this

答案 1 :(得分:1)

  var table = $('#example').DataTable({
       ....       
      "initComplete": function(oSettings) {
         $(this).on('click', "i.fa.fa-minus-square", function(e) {
           table.row( $(this).closest('tr') ).remove().draw();
         });
      ....
  });

在这里,第一个this被引用到#example,因此将其替换。第二个this引用到i.fa.fa-minus-square,即您绑定单击的元素。因此,请相应地替换它。

   $(this).on('click', 'i.fa.fa-pencil-square', function(e){
        var rowData = table.row($(this).closest('tr')).data();

这里是相同的。第一个this#example,第二个是i.fa.fa-pencil-square

依此类推

问题:为什么只使用箭头功能?在需要它们的地方使用它们,而不是在使代码复杂的地方使用它们。当您有类并定义需要使用class访问this的类方法时,箭头函数非常有用。在这里,就您而言,我看不出您应该使用它们的任何理由。

如果要对initComplete使用单独的函数,则可以传递this作为参数。例如:"initComplete": myFunction(this)然后使用它function myFunction(elem) { console.log(elem) }将返回#example