【问题标题】:Update HTML attribute from appended HTML element从附加的 HTML 元素更新 HTML 属性
【发布时间】:2018-06-21 05:56:06
【问题描述】:

用户正在添加一个新的搜索字段(输入字段 + 选择元素)。当用户从选择元素中选择时,我试图从输入元素中更新“名称”值。不幸的是,以下代码导致 console.log 行出现以下错误

TypeError: null is not an object (evaluating 'document.getElementById(selectID).options')

代码如下:

function updateName2(index){

  var selectID = "SEL"+index;
  var inputID = "AS"+index;

  var e = document.getElementById(selectID);
  var valueSelect = e.options[e.selectedIndex].text;

  console.log(valueSelect); //error here

  document.getElementById(inputID).name = valueSelect;
};

var index = 2;

// ADD NEW SEARCH FIELD
$("#addNewSearchField").click(function() {
$("#Form").append(

  "<input id='AS"+index+"' type='text' name='' value=''>"+
  "<select id='SEL"+index+"' onChange='updateName2(index)'>"+
      "<?php
      foreach ($fields as $key => $value) {
        if($key=="select"){
          echo "<option selected value='".$key."'>".$value."</option>";
        }else{
          echo "<option value='".$key."'>".$value."</option>";}
        };
      ?>"
   +"</select><br>"
);
index += 1;
})

【问题讨论】:

  • 尝试console.log(e) 应该是null 女巫解释其余部分。
  • @NikolaAndreev 是的,它给出了TypeError: null is not an object (evaluating 'e.options'),所以它根本找不到对象?
  • 有人发布并删除了一个建议 updateName2(index) 应该是 updateName2('+index+') 的答案,我同意,但我不认为这是您问题的根源。
  • @NappingRabbit 我起初删除了我的答案,因为我认为我误读了代码。我现在已经正确阅读了代码,并取消了删除并稍微编辑了答案。
  • 因此,如果您进行修复并注释掉以下行:var valueSelect...document.getElement... 那么 console.log(e) 你会得到什么?

标签: javascript jquery


【解决方案1】:

创建选择块时

"<select id='SEL"+index+"' onChange='updateName2(index)'>"+

您在其id 中使用了index 变量,但在onChange 中的函数中您只是使用index 作为字符串,它没有正确引用该变量。这意味着您正在运行document.getElementById("SEL" + undefined),它返回null(因为这样的元素不存在)。

试试这个:

"<select id='SEL"+index+"' onChange='updateName2(" + index + ")'>"+

【讨论】:

  • 明星!像魅力一样工作。出于某种原因,我想到了它,并且确定将其保留为字符串。学过的知识。谢谢!
猜你喜欢
  • 1970-01-01
  • 2010-10-17
  • 2019-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多