[英]How to call javascript function from html?
我有以下代码:
<ion-content>
<ion-list>
<ion-item ng-repeat="x in names|orderBy:'order_id'">
{{ x.order_id + ', ' + x.table_id+', '+x.name+', '+x.phone+', '+x.address+', '+x.remark+', '+myFunction(x.ctime)}}
</ion-item>
</ion-list>
</ion-content>
我想调用myFunction并获取返回的值,但是它不起作用。
<script type="text/javascript">
function myFunction(ctime) {
alert("Hello World!");
// create a new javascript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds
var date = new Date(ctime*1000);
// hours part from the timestamp
var hours = date.getHours();
// minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
console.log("debug",formattedTime);
return formattedTime;
}
</script>
我想知道问题出在哪里。 谢谢。
您的页面中附加script
的顺序以及对expression
的求值可能是问题所在。
无论如何,实际上不建议直接在html文件中创建全局JavaScript
函数。 您正在使用AngularJS
,可以在相关scope
使用该功能,它将自动为您处理。
您必须在声明对象数组names
位置有一个controller
,该controller
外观必须类似于:
myApp.controller('NamesCtrl', ['$scope', function($scope) {
$scope.names = [{order_id: 1, table_id: 4, name: "Someone"}];
}]);
只需将myFunction
添加到控制器的范围内,例如:
myApp.controller('NamesCtrl', ['$scope', function($scope) {
$scope.names = [{order_id: 1, table_id: 4, name: "Someone"}];
$scope.myFunction = function myFunction(ctime) {
alert("Hello World!");
// create a new javascript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds
var date = new Date(ctime*1000);
// hours part from the timestamp
var hours = date.getHours();
// minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
console.log("debug",formattedTime);
return formattedTime;
};
}]);
调用函数所用的表达式无需更改。
如果您想要有关此概念的更多详细信息,可以在这里查看 。
如果您仍然选择将script
保留在html页面中,则可以尝试在表达式之前包含该脚本,并检查其是否解决了问题。
如果仍有任何问题,请随时发表评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.