javascript对象仅警报第一个选项
您好,我正在处理Javascript中的一个对象。这是一个单独的.js文件中的我的对象 json-webservice.jsjavascript对象仅警报第一个选项,javascript,oop,object,Javascript,Oop,Object,您好,我正在处理Javascript中的一个对象。这是一个单独的.js文件中的我的对象 json-webservice.js //create object function objdata(tool, product, details) { //create object properties this.tool = tool; this.product = product; this.details = details; //cre
//create object
function objdata(tool, product, details) {
//create object properties
this.tool = tool;
this.product = product;
this.details = details;
//create object methods
this.validate = function () {
var error = 0;
for (var prop in this) {
if (this.hasOwnProperty(prop)) {
if (prop != 'validate' || prop != 'submit') {
if (this[prop] == null || this[prop] == undefined || this[prop] == "") {
error += 1;
}
}
}
}
return error;
}
this.submit = function () {
var error = this.validate();
if (error > 0) {
alert("errors: " + error);
}
else {
alert(this.tool + " " + this.product + " " + this.details);
}
}
}
}
我将此脚本包含在我的页面index main.html
的标题中
然后文档准备就绪,然后初始化新对象并提交
$(document).ready(function () {
var userdata = new objdata('5', 'Main Page', '9');
userdata.submit();
});
我的问题是,为什么它只发出警报
---------------------------
Windows Internet Explorer
---------------------------
5
---------------------------
OK
---------------------------
而不是
---------------------------
Windows Internet Explorer
---------------------------
5 Main Page 9
---------------------------
OK
---------------------------
就像我认为应该的那样。我的物品编码正确吗?我没有在IE中报告任何javascript错误
wierd的一部分是我可以复制json-webservice.js文件内容(上面的对象),它工作得非常好。但它不能作为外部文件使用。您需要使用
此[prop]
而不是此.prop
;前者查找名称为prop
中字符串的属性,而后者查找名称字面上为“prop”的属性
(我无法让它重现您的输出。如前所述,它只是发出“错误”警报,而上面的更改导致它给出了所需的输出。)考虑使用
console.log()
(和真正的浏览器)而不是alert()
进行调试。您可能可以将if
语句简化为if
语句(!this.prop)哦,我很想去!可惜这份工作我只有IE7¬o( ̄- ̄メ)我更改了一些代码。我认为逻辑现在是正确的。我遇到的问题是,当对象位于外部.js文件中时,同样的输出无效。您如何在中调用它?外部文件中的代码是否与上面显示的完全相同?我修改了问题,以澄清对象文件中的内容。有什么建议吗?