javascript 仅在复选框被选中时调用函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21073605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call function only when check box is checked
提问by user1371896
I am new to angular.js and I was trying to create an html list with checkboxes, so what I was trying to achieve was to call a javascript function, when a user checks a checkbox.
我是 angular.js 的新手,我试图创建一个带有复选框的 html 列表,所以我试图实现的是在用户选中复选框时调用 javascript 函数。
<input id='box' ng-model='" + key + "' ng-change='graphquery(\"" + key + "\")' class = 'queryNameList css-checkbox' type = 'checkbox' />
So here, I have used ng-change
which basically captures all changes, it calls function graphquery
on both cases ( checking and unchecking)
所以在这里,我使用了ng-change
它基本上捕获了所有更改,它graphquery
在两种情况下调用函数(选中和取消选中)
Is it possible to specify, condition, like it should only call this function if the checkbox is checked.
是否可以指定条件,就像它应该只在选中复选框时调用此函数。
采纳答案by Oleg Belousov
$scope.graphquery = function(key){
if(!$scope[key]){
//do nothing
return;
}
//do something
}
回答by a better oliver
ng-change="!key || graphQuery(key)"
If the checkbox is checked then !key
resolves to false
, so graphQuery(key)
is executed.
如果复选框被选中,则!key
解析为false
,因此graphQuery(key)
被执行。
If the checkbox is unchecked then !key
resolves to true
, so anything after ||
is ignored;
如果复选框未选中,则!key
解析为true
,因此||
忽略之后的任何内容;
回答by M.K. Safi
Check this examplefrom the documentation.
从文档中查看此示例。
ngModel on a checkbox seems to either be true
or false
and that's what gets passed to the function that you specify in ngChange
. If you want to specify a truth value or a falseness value, you can use the ngTrueValue
and ngFlaseValue
directives.
复选框上的 ngModel 似乎要么是true
要么false
这就是传递给您在ngChange
. 如果要指定真值或假值,可以使用ngTrueValue
和ngFlaseValue
指令。
See this Plunk.
看到这个Plunk。
var app = angular.module('plunker', []);
app.controller('MainCtrl',
function($scope) {
$scope.graphQuery = function(key) {
if (key)
$scope.key = key
}
$scope.returnKey = function() {
return '123'
}
}
)
And in HTML
在 HTML 中
<body ng-controller="MainCtrl">
<input id='box' ng-model='key' ng-change='graphQuery()' class='queryNameList css-checkbox'
type='checkbox' ng-true-value="{{returnKey()}}" />
<pre>Key: {{key}}</pre>
</body>
So, what you want to do is check if the value of key
is true
or false
and only execute your code when the value is true
and you can specify a function in ng-true-value
to return a string in case of true
.
因此,您想要做的是检查 的值是否key
为true
或false
并且仅在值为时才执行您的代码,true
并且您可以指定一个函数ng-true-value
在 的情况下返回字符串true
。
回答by Mr_NAIF
document.getElementById('box').addEventListener('change', function(){
if(this.checked === true) runMyFunction();
});