小编gal*_*ong的帖子

Javascript'this'在对象内部返回未定义

我有以下代码:

let myObj = {
  foo: "bar",
  getFoo: function() {
    console.log(this.foo);
  },
  method: function() {
    if (true) {
      window.addEventListener('scroll', this.getFoo);
    } else {
      window.removeEventListener('scroll', this.getFoo);
    }
  }
}

window.addEventListener('click', () => {
  myObj.method();
});
Run Code Online (Sandbox Code Playgroud)

它返回 undefined,因为(出于我未知的原因)如果在函数中作为回调调用,则this引用该window对象。现在如果我在里面使用了一个箭头函数-getFooaddEventListenermyObj.method

window.addEventListener('scroll', () => {
  this.getFoo();
});
Run Code Online (Sandbox Code Playgroud)

这行得通,但后来我调用了一个匿名函数,以后就不能了removeEventListener。我怎么能用非匿名函数来完成这个工作?

javascript object this ecmascript-6 arrow-functions

7
推荐指数
2
解决办法
6649
查看次数

包装弹性项目之间不需要的空间

当我将弹性容器的高度设置为大于弹性项目所占据的高度时,包裹的项目之间会留有空间。请注意 - justify-content 和align-items 都设置为flex-start。这是片段(运行后单击整页)

.flex-container {
  min-height: 100vh;
  position: relative;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: flex-start;
  flex-wrap: wrap;
}
header,
main,
aside,
footer {
  padding: 1rem;
  background-color: tomato;
}
header,
footer {
  width: 100%;
}
main {
  width: 75%;
}
aside {
  flex-grow: 1;
}
Run Code Online (Sandbox Code Playgroud)
<div class="flex-container">
  <header>Header Content</header>
  <main>Main content here.</main>
  <aside>Sidebar content</aside>
  <footer>Footer Content</footer>
</div>
Run Code Online (Sandbox Code Playgroud)

这是笔

flex-direction: column;如果您反转所有属性,则可以重现这一点。这是预期的行为吗?如果是这样,为什么?有没有办法让我解决这个问题并得到类似的东西:

在此输入图像描述

将 flex-container 高度设置为 100vh ?

css flexbox

3
推荐指数
1
解决办法
2507
查看次数

在预定义函数内访问的全局变量返回null -javascript

出于某种原因,我无法访问变量.可能是范围问题,或时间问题,无法找到它.这是我的简化代码:

var endResult = "";

//function loads html into given element.Called as a callback later when google maps direction service is done//
function getResults(){
  $.ajax({
    url:'foo.php',
    data: endResult,
    //etc., response loaded asynchronously in div element//
  });
}

//when form is submitted
$('#form').submit(function(){
  var endResult = "";
  //get form data, define variable//
  $.post('bar.php',function(data){
    var location = data;
    //initialize Maps Directions Service//
    var directionService = new google.maps.DirectionsService();
    //function gets directions, and loads a single value into global variable "endResult"//
    function calcRoute(){
      var …
Run Code Online (Sandbox Code Playgroud)

javascript ajax jquery google-maps scope

-1
推荐指数
1
解决办法
451
查看次数