使用错误的属性调用对象

时间:2017-01-20 18:08:24

标签: javascript jquery html

我目前正在建立一个像PCPartPicker这样的网站,但是为学校项目的水冷部件。我潜入水中,我遇到了一些问题。最重要的是: 这是我的对象构造函数启动

var cpuCollection = [];
var myComputer = [];
function CPU(frequency,cores,socket,name) {
    this.name = name;
    this.frequency = frequency;
    this.cores = cores;
    this.socket = socket;

    cpuCollection.push(this);
}

var i75930k = new CPU(3.6, 6, 2011.3, "i7 5930k");  
var i54690k = new CPU(3.6, 4, 1150, "i5 4960k");`

在构建对象构造函数后,我使用真实的计算机部件制作了一些测试对象。<​​/ p>

在我的HTML中,我使用以下代码下载了加载对象填充的菜单:

$(cpuCollection).each(function() {
    $('#cpusel').append($("<option> " + this.name + "</option>"))
});

从那里我想做到这一点,当在下拉列表中选择一个选项时,正确的对象将被推入myCPU var以便在另一个函数中进行兼容性测试。我用来完成此任务的代码如下:

 $('#cpusel').change(function() {
    myCPU = new CPU();
    $(cpuCollection).each(function(){
       if(this.name = $('#cpusel :selected').text()) {
          myCPU = this;
       }
    });
 });

不幸的是,此代码目前无法正常工作,并且当myCPU.socket被选中时1150 i75930k确实应该为2011.3时告诉我[HttpPost] [ValidateAntiForgeryToken] public ActionResult Save(Survey survey, List<Category> category, List<Question> question, List<Answer> answer) { if (survey.SurveyId == 0) { _context.Surveys.Add(survey); foreach (var categorytoAdd in category) _context.Categories.Add(categorytoAdd); foreach (var questiontoAdd in question) _context.Questions.Add(questiontoAdd); foreach (var answertoAdd in answer) _context.Answers.Add(answertoAdd); } else { foreach (var surveyInDb in _context.Surveys.Where(m => m.SurveyId == survey.SurveyId)) surveyInDb.Description = survey.Description; //old code before switching to a list //foreach (var categoryInDb in _context.Categories.Where(m => m.CategoryId == category.CategoryId)) //categoryInDb.CategoryDescription = category.CategoryDescription; //foreach (var questionInDb in _context.Questions.Where(m => m.QuestionId == question.QuestionId)) // questionInDb.QuestionText = question.QuestionText; //foreach (var answerInDb in _context.Answers.Where(m => m.AnswerId == answer.AnswerId)) // answerInDb.AnswerText = answer.AnswerText; foreach (var categorytoAdd in category) { foreach (var categoryInDb in _context.Categories.Where(m => m.CategoryId == categorytoAdd.CategoryId)) categoryInDb.CategoryDescription = categorytoAdd.CategoryDescription; } foreach (var questiontoAdd in question) { foreach (var questionInDb in _context.Questions.Where(m => m.QuestionId == questiontoAdd.QuestionId)) questionInDb.QuestionText = questiontoAdd.QuestionText; } foreach (var answertoAdd in answer) { foreach (var answerInDb in _context.Answers.Where(a => a.AnswerId == answertoAdd.AnswerId)) answerInDb.AnswerText = answertoAdd.AnswerText; } } _context.SaveChanges(); return RedirectToAction("Index", "Surveys"); } @using (Html.BeginForm("Save", "Surveys")) { <div class="form-group"> @Html.LabelFor(s => s.SurveyId) @Html.TextBoxFor(s => s.Description, new { @class = "form-control" }) @Html.ValidationMessageFor(s => s.Description) </div> <div id="Survey" class="form-group"> @foreach (var category in Model.Categories.Where(c => c.SurveyId == Model.SurveyId)) { <ul>@Html.LabelFor(c => category.CategoryId)</ul> <ul>@Html.TextBoxFor(c => category.CategoryDescription, new { @class = "form-control" })</ul> @Html.HiddenFor(c => category.CategoryId) @Html.HiddenFor(c => category.CategoryDescription) foreach (var question in Model.Questions.Where(q => q.CategoryId == category.CategoryId)) { <ul>@Html.LabelFor(q => question.QuestionId)</ul> <ul>@Html.TextBoxFor(q => question.QuestionText, new { @class = "form-control" })</ul> @Html.HiddenFor(q => question.QuestionId) @Html.HiddenFor(q => question.QuestionText) foreach (var answer in Model.Answers.Where(a => a.QuestionId == question.QuestionId)) { <ul>@Html.LabelFor(a => answer.AnswerId)</ul> <ul>@Html.TextBoxFor(a => answer.AnswerText, new { @class = "form-control" })</ul> @Html.HiddenFor(a => answer.AnswerId) @Html.HiddenFor(a => answer.AnswerText) } } } </div> @Html.HiddenFor(m => m.SurveyId) @Html.AntiForgeryToken() <button type="submit" class="btn btn-primary">Save</button> } 。我在这里结束了,想要取得一些进展。 感谢您的帮助。

编辑:我修正了等号问题,现在我认为问题可能源于我将对象推入cpuCollection数组的方式。当我尝试记录cpuCollection时,我得到[CPU,CPU],这显然不是我想要的。如何将创建时的CPU对象推送到cpuCollection,并使其所有属性保持不变。

3 个答案:

答案 0 :(得分:0)

在if()语句中尝试:

$('#cpusel').change(function() {
myCPU = new CPU();
$(cpuCollection).each(function(){
   if(this.name === $('#cpusel :selected').text()) {
      myCPU = this;
   }
});

答案 1 :(得分:0)

因此,您的某些逻辑/语法存在一些问题,我将尝试单独解决这些问题,以便您更好地了解我如何获得可行的解决方案:

1)您正在从对象定义中将元素推送到数组。这通常是不好的做法,因为它不可重用,并且如果在实例化CPU对象的实例之前未定义名为cpuCollection的数组,则会抛出错误。最好说cpuCollection.push(new CPU(...));

2)当您将选项附加到下拉列表时,您还应添加value属性,这样您就可以更轻松地获取#3中的值

3)如果您在<option>元素上设置值属性,则无需查找所选选项的文本,您可以将选择器简化为$('#cpusel').val()

4)没有必要通过说$(cpuCollection).each(...)将数组包装在jQuery对象中,你可以(并且应该)使用内置的vanilla javascript数组操作。

5)我将更改处理程序中的.each()更改为.some()这是因为当您从.some()返回true时,它会停止任何进一步的迭代,这就是您想要的。以前,它会继续循环到最后,即使它已经找到了匹配的CPU。

6)我添加了一个myCPU变量并将其实例化为null,因此如果您在严格模式下运行,则更改处理程序不会为之前未定义的变量引发错误。

7)你的if语句中的逻辑正在进行分配,而不是比较,因为你使用=代替== or ===,这是一个简单的错误。

希望这有帮助!

var cpuCollection = [];
var myComputer = [];
var myCPU = null;
function CPU(frequency,cores,socket,name) {
  this.name = name;
  this.frequency = frequency;
  this.cores = cores;
  this.socket = socket;
}

cpuCollection.push(new CPU(3.6, 6, 2011.3, "i7 5930k"));  
cpuCollection.push(new CPU(3.6, 4, 1150, "i5 4960k"));

cpuCollection.forEach(function(cpu, index) {
  $('#cpusel').append($('<option value="'+ cpu.name + '">'  + cpu.name + '</option>'))
});

$('#cpusel').change(function() {
  myCPU = new CPU();
  cpuCollection.some(function(cpu, index){
    if(cpu.name === $('#cpusel').val()) {
      myCPU = cpu;
      return true;
    }
  });
  console.log(myCPU);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="cpusel"></select>

答案 2 :(得分:0)

有简单的方法:

var cpuCollection = [];
var myComputer = [];

function CPU(frequency,cores,socket,name) {
    cpuCollection.push({
        name:      name,
        frequency: frequency,
        cores:     cores,
        socket:    socket
    });
}

var i75930k = CPU(3.6, 6, 2011.3, "i7 5930k");  
var i54690k = CPU(3.6, 4, 1150,   "i5 4960k");

$(cpuCollection).each(function(i,cpu) {
    var option = $('<option/>').html(cpu.name).data('cpu',cpu);
    $('#cpusel').append(option);
});

$('#cpusel').change(function() {

    var selected = $(this).find('option:selected'); 
    var text = $(selected).text();
    var myCPU;

    // You can simply use : myCPU = $(selected).data("cpu")
    console.log('via data:',$(selected).data("cpu"));

    $(cpuCollection).each(function(i,cpu){
        if($.trim(cpu.name) == $.trim(text)) {
           myCPU = cpu;
           // return false; ==> break the each();
        }
    });
    console.log('via each:',myCPU);
}); 

请参阅此demo