[英]Initialize javascript Object literal property Dynamically
I wanted to define the input values from HTML page as javascript Literal object property but i am getting Undefined error on accessing in JS file. 我想将HTML页面的输入值定义为javascript Literal对象属性,但是在JS文件中访问时出现未定义错误。
Suppose i have a input value like as in HTML 假设我有一个类似HTML的输入值
<input type="hidden" id="someid" value="dbvalues in arrayform" >
<input type =“ hidden” id =“ someid” value =“数组形式的dbvalues”>
Now this value i am trying to define like (A.js) as below: 现在,我正在尝试将此值定义为(A.js),如下所示:
var abc = {
x : $("#someid").val(),
y: function (){
console.log(this.x);
}
}
Now when in another JS file (B.js) i call it as 现在当在另一个JS文件(B.js)中时,我将其称为
console.log(abc.x());
console.log(abc.x());
Any Solutions? 有解决方案吗?
x
is not function, it is string
. x
不是函数,它是string
。
You should call it as: 您应该将其称为:
console.log(abc.x);
two things - first of all it would not be console.log(abc.x());
两件事-首先它不是
console.log(abc.x());
x()
is how you call a function, you could call abc.y()
; x()
是调用函数的方式,可以调用abc.y()
; though since it's a function. 尽管这是一个功能。
the other thing is that jQuery must be loaded, and that this code defining var abc = {
has to be executed after the DOM is fully loaded 另一件事是必须加载jQuery,并且必须在DOM完全加载后执行此定义
var abc = {
代码
I think you want this: 我想你想要这个:
$(function(){ // this ensures DOM is ready, careful about where you want to call abc from though;
var abc = {
var me = this;
x : function(){ return $("#someid").val()},
y: function (){
console.log(me.x); // try this instead it will help with 'this' confusion
}
}
});
now you can call 现在你可以打电话
console.log(abc.x());
A.js A.js
var abc;
$(function() {
abc = {
x: $("#someid").val(),
y: function (){
console.log(this.x);
}
}
});
B.js B.js
$(function() {
abc.y();
});
Note that $("#someid").val()
will return a string, so you may need to convert into into an array. 请注意,
$("#someid").val()
将返回一个字符串,因此您可能需要转换为数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.