JS/jQuery 原型设计问题,可能的范围问题
JS/jQuery Prototyping Issue, possible scoping concerns
感谢您的阅读。我有一个jQuery函数,我想做原型。该函数只是将隐藏/显示函数绑定到复选框。每个复选框对应于要隐藏的不同元素。我一直在控制台日志记录,并且正在创建对象;控制台上没有其他错误。此函数的工作原理是:
$("input[name='fcrBox']").bind('change', function(){
if( $(this).is(':checked')){
$("#result").show();
} else {
$("#result").hide();
}
});
但这不会:
function HideShow(elem, affected) {
this.elem = elem;
this.affected = affected;
}
var fcrBox = new HideShow('input[name="fcrBox"]', '#result');
var sc = new HideShow('input[name="sc"]', '#MQSresult');
console.log(fcrBox);
console.log(sc);
HideShow.prototype.binder = function(elem, affected){
$(elem).bind('change', function(){
if( $(this).is(':checked')){
$(affected).show();
} else {
$(affected).hide();
}
});
}
fcrBox.binder();
sc.binder();
谢谢!任何意见将不胜感激。
您使用两个参数(elem
和 affected
(定义了 binder
,但在调用该方法时不会传递任何值。
如果要访问已传递给构造函数并分配给对象的值,则必须显式访问这些值。这些值不会神奇地传递给binder
。
function HideShow(elem, affected) {
this.elem = elem; // <-----------------------------------------------|
this.affected = affected; // |
} // |
// |
var fcrBox = new HideShow('input[name="fcrBox"]', '#result'); // |
var sc = new HideShow('input[name="sc"]', '#MQSresult'); // |
// |
console.log(fcrBox); // |
console.log(sc); // |
// |
HideShow.prototype.binder = function(){ // |
var self = this; // reference to the instance; this is the same as --|
$(self.elem).bind('change', function(){
// In the event handler, `this` refers to the DOM element, not the
// `HideShow` instance. But we can access the instance via `self`.
if( $(this).is(':checked')){ // shorter: this.checked
$(self.affected).show();
} else {
$(self.affected).hide();
}
});
}
fcrBox.binder();
sc.binder();
相关文章:
- setInterval游戏循环的范围问题
- Javascript innerHTML超出范围的问题
- AngularJs避免范围界定问题
- firefox中的Javascript事件范围问题
- AngularJS指令范围约束问题重复出现
- jQuery“this”范围问题
- 可以't在quizz页面范围问题上用最终分数更新变量
- JavaScript 函数变量范围问题
- 奇怪的可变范围问题
- JavaScript 中变量范围的问题
- 主干.js(具有 Require.js)变量/范围访问问题
- 递归承诺调用 - 内存范围变量问题
- JQuery 范围滑块步进更改问题
- AngularJS中的范围问题
- 如何在 JavaScript for D3.js 中解决这样的范围问题
- 我可以设置这个吗'某事'在该服务中动态创建的嵌套对象中的服务?(可能是范围问题)
- Highcharts列范围工具提示问题
- 在函数中提示未定义返回.(问题)范围
- 访问Javascript's变量:涉及Javascript, JQuery和PHP/MySQL的问题&范围
- JavaScript 闭包问题..范围