如何在命名函数 change() 中获取 prop('checked') this
How to get prop('checked') this inside named function change()
好的,所以我正在检查检查的 属性 值是真还是假。
下面的代码效果很好:
var $artistip = null;
var $chkbx = $('input[name="artist"]');
$chkbx.change( function(){
var $checked = $(this).prop('checked');
if($checked) {
$artistip = $(this).val();
}else {
$artistip = null;
}
});
我想将所有代码转换为命名函数,例如:
$djchkbx.change( function() {
getCheckBoxValue($djchkbx,$djtip);});
var $djtip = null;
var $djchkbx = $('input[name="dj"]');
function getCheckBoxValue(thisckbox, $uniqueVariable){
var $checked = $djchkbx.prop('checked');
console.log($checked);
if($checked) {
$uniqueVariable = $(this).val();
console.log('Checked');
console.log($uniqueVariable);
}else {
$uniqueVariable = null;
console.log('Un Checked');
console.log($uniqueVariable);
}
}
问题是我总是报错。
原始代码很有魅力。
我正在创建的命名函数没有按预期工作,只是 returns false。
我将大量使用该代码,因为我有多个输入复选框需要检查。
所以我真的很想做一个和我原来的代码一样的可重用函数。
首先,清理你的代码。将所有 var
声明移至顶部。然后删除 getCheckBoxValue
的函数参数 - 你无论如何都不要使用它们,或者至少不要以明智的方式使用它们。在你的 change
处理程序中调用你的命名函数,如下所示:
getCheckBoxValue.call(this);
这样,命名函数中的 this
将与事件处理程序中的 this
相同。
在您的命名函数中,您可以像在顶部代码片段中一样访问复选框元素:$(this)
将 $(this).val()
或 null
直接分配给 $djtip
- 分配给函数参数没有任何意义。如果您不能直接分配给 $djtip
因为命名函数在不同的上下文中使用,那么 return 值并在匿名事件处理函数中进行分配。
好的,所以我正在检查检查的 属性 值是真还是假。 下面的代码效果很好:
var $artistip = null;
var $chkbx = $('input[name="artist"]');
$chkbx.change( function(){
var $checked = $(this).prop('checked');
if($checked) {
$artistip = $(this).val();
}else {
$artistip = null;
}
});
我想将所有代码转换为命名函数,例如:
$djchkbx.change( function() {
getCheckBoxValue($djchkbx,$djtip);});
var $djtip = null;
var $djchkbx = $('input[name="dj"]');
function getCheckBoxValue(thisckbox, $uniqueVariable){
var $checked = $djchkbx.prop('checked');
console.log($checked);
if($checked) {
$uniqueVariable = $(this).val();
console.log('Checked');
console.log($uniqueVariable);
}else {
$uniqueVariable = null;
console.log('Un Checked');
console.log($uniqueVariable);
}
}
问题是我总是报错。
原始代码很有魅力。 我正在创建的命名函数没有按预期工作,只是 returns false。
我将大量使用该代码,因为我有多个输入复选框需要检查。 所以我真的很想做一个和我原来的代码一样的可重用函数。
首先,清理你的代码。将所有 var
声明移至顶部。然后删除 getCheckBoxValue
的函数参数 - 你无论如何都不要使用它们,或者至少不要以明智的方式使用它们。在你的 change
处理程序中调用你的命名函数,如下所示:
getCheckBoxValue.call(this);
这样,命名函数中的 this
将与事件处理程序中的 this
相同。
在您的命名函数中,您可以像在顶部代码片段中一样访问复选框元素:$(this)
将 $(this).val()
或 null
直接分配给 $djtip
- 分配给函数参数没有任何意义。如果您不能直接分配给 $djtip
因为命名函数在不同的上下文中使用,那么 return 值并在匿名事件处理函数中进行分配。