【问题标题】:Change Values of Global Variable with $scope function使用 $scope 函数更改全局变量的值
【发布时间】:2020-04-29 12:54:51
【问题描述】:

我定义了两个 Date 类型的全局变量,并在函数中更改了值,但不知何故,在运行函数后,全局变量的值没有采用新值。问题是什么? 提前致谢!

var value1 = new Date()
var value2 = new Date()
var $scope = self.ctx


$scope.settimes = function() {
value1.setSeconds(0)
value1.setMinutes(15)
value1.setHours(6)

value2.setSeconds(0)
value2.setMinutes(30)
value2.setHours(12)

}

console.log(value1)
console.log(value2) //value1 and value2 still have the same value =new Date() but not be assigned with the values within the function
<button ng-click="settimes()">Change Time</button> 

【问题讨论】:

  • 对我来说,self.ctx 返回 undefined 所以脚本返回错误。您可以一次性设置时间值(也可以将毫秒数归零):value1.setHours(6, 15, 0, 0).

标签: javascript html date momentjs


【解决方案1】:

您的console.log 需要在函数内部。 代码将从上到下运行,您定义函数然后立即调用console.log。但是值只有在你点击按钮后才会改变,所以你需要检查函数内部的值。

var value1 = new Date()
var value2 = new Date()
var $scope = self.ctx


$scope.settimes = function() {
  value1.setSeconds(0)
  value1.setMinutes(15)
  value1.setHours(6)

  value2.setSeconds(0)
  value2.setMinutes(30)
  value2.setHours(12)

  console.log(value1)
  console.log(value2)
}

 //value1 and value2 still have the same value =new Date() but not be assigned with the values within the function
<button ng-click="settimes()">Change Time</button>

【讨论】:

  • 如果这个答案对你有帮助,请考虑“接受”它;这会将您的问题标记为已解决,并奖励您和回答者一些声誉 - How does accepting an answer work
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-04
  • 2013-10-04
  • 1970-01-01
  • 1970-01-01
  • 2014-01-31
相关资源
最近更新 更多