简体   繁体   English

Javascript通过getElementbyId访问动态创建的元素

[英]Javascript accessing dynamically created element via getElementbyId

I'm playing around with Javascript as a hobby and I've been having trouble accessing elements that I have dynamically created via another function. 我将Javascript作为一种业余爱好,并且在访问通过其他函数动态创建的元素时遇到了麻烦。

Essentially, I have a link that dynamically creates a couple of dropdown selects with a few options. 本质上,我有一个链接可以动态创建几个带有几个选项的下拉选择。 Then I have a second link which I would try to print some of the selected options onto console. 然后,我有第二个链接,我将尝试将某些选定的选项打印到控制台上。

HTML: HTML:

<a href="#" id="make" onclick="maker()">create</a>
<a href="#" id="get" onclick="getter()">collect</a>
<div id="box"><br>

Javascript: 使用Javascript:

function maker() {
    box.appendChild(document.createElement("br"));
    for (i = 0; i < 2; i++) {
      box.appendChild(document.createTextNode("test " + (i + 1) + " "));
      for (k = 0; k < 2; k++) {
        var dropdown = document.createElement("select");
        box.appendChild(dropdown);
        for (j = 0; j < nice.length; j++) {
          var option = document.createElement("option");
          option.value = nice[j];
          option.text = nice[j];
          option.id = 'option' + i + k;
          console.log(option.id)
          dropdown.appendChild(option);
        }
      }
      box.appendChild(document.createElement("br"));
    }
}

function getter() {
  var test = document.getElementById("option01");
  console.log(test.options[test.selectedIndex].value);
}

I've printed to console the option id's as they are created (seems to have no problem printing this), and added them to the DOM via appendChild. 我已经打印了创建选项ID的控制台(打印此选项似乎没有问题),并通过appendChild将它们添加到DOM中。 However with my second function, I am unable to retrieve the selected value of the options despite explicitly referencing the id. 但是,使用第二个功能,尽管显式引用了ID,但我无法检索选项的选定值。

My guess is that it has something to do with the order the scripts are loaded. 我的猜测是,这与脚本加载的顺序有关。 Can anyone help me understand what's going on? 谁能帮助我了解发生了什么事?

Attached is my JSFiddle file, http://jsfiddle.net/c8h6gx2d/1/ 附件是我的JSFiddle文件http://jsfiddle.net/c8h6gx2d/1/

Cheers, 干杯,

The problem is that <option> s are nested inside of <select> s, and it's the * <select> *s which have a selectedIndex property. 问题是<option>嵌套在<select> ,而* * <select> *则具有selectedIndex属性。 So, test.options[test.selectedIndex].value won't work when test is an <option> element. 因此,当test<option>元素时, test.options[test.selectedIndex].value将不起作用。 Try using getElementById to get one of the <select> s, for one, and then just access its .value (which is less cumbersome than checking selectedIndex ): 尝试使用getElementById来获取<select>之一,然后仅访问其.value (这比检查selectedIndex麻烦得多):

 var nice = [2, 3, 5]; function maker() { box.appendChild(document.createElement("br")); for (i = 0; i < 2; i++) { box.appendChild(document.createTextNode("test " + (i + 1) + " ")); for (k = 0; k < 2; k++) { var dropdown = document.createElement("select"); dropdown.id = 'select' + i; box.appendChild(dropdown); for (j = 0; j < nice.length; j++) { var option = document.createElement("option"); option.value = nice[j]; option.text = nice[j]; dropdown.appendChild(option); } } box.appendChild(document.createElement("br")); } } function getter() { var test = document.getElementById("select0"); console.log(test.value); // same as: // console.log(test.options[test.selectedIndex].value); } 
 <a href="#" id="make" onclick="maker()">create</a> <a href="#" id="get" onclick="getter()">collect</a> <div id="box"><br> 

Also note that duplicate IDs in a single document is invalid HTML , so if you ever call maker more than once, for your HTML to be valid, you might have a separate counter outside of maker that gets incremented: 还要注意,单个文档中的重复ID是无效的HTML ,因此,如果您多次呼叫maker ,为了使HTML有效,您可能 maker 之外有一个单独的计数器,该计数器会递增:

const makeCount = 0;
function maker() {
  // ...
      dropdown.id = 'select' + makeCount + '_' + i;
  // ...
  makeCount++;
}

(or, avoid IDs entirely, if at all possible, numeric ID indicies are a code smell - use classes instead) (或者,完全避免使用ID,如果可能的话,数字ID索引是代码的味道-请改用类)

We need to discriminate between option elements and the select element. 我们需要区分选项元素和选择元素。 The select element is the one with which you want to interact most of the time, and the option elements are simply a collection of possible entries for the select element. select元素是大多数时间要与之交互的元素,而option元素只是select元素可能条目的集合。

Your code as it stands now generates these sort of elements: 现在,您的代码将生成以下类型的元素:

<select>
    <option value="2" id="option00">2</option>
    <option value="3" id="option00">3</option>
    <option value="5" id="option00">5</option>
</select>

As you see all the options receive the same ID - which is generally forbidden in HTML documents. 如您所见,所有选项都接收到相同的ID-HTML文档中通常禁止使用该ID。 You might consider moving the ID indicator to the select element, which also gives you access to the value of the selected option. 您可能考虑将ID指示器移动到select元素,这也使您可以访问选定选项的值。

Here is the revised JS code with comments before revisions: 这是经过修订的JS代码,其中包含修订前的注释:

var nice = [2, 3, 5];

  function maker() {
    box.appendChild(document.createElement("br"));
    for (i = 0; i < 2; i++) {
      box.appendChild(document.createTextNode("test " + (i + 1) + " "));
      for (k = 0; k < 2; k++) {
        var dropdown = document.createElement("select");
        # Giving the select item an ID instead of each option
        dropdown.id = 'select' + i + k;
        box.appendChild(dropdown);
        for (j = 0; j < nice.length; j++) {
          var option = document.createElement("option");
          option.value = nice[j];
          option.text = nice[j];
          option.id = 'option'
          console.log(option.id)
          dropdown.appendChild(option);
        }
      }
      box.appendChild(document.createElement("br"));
    }
  }

  function getter() {
    # Getting the select element instead of the option 
    var selectElement = document.getElementById("select00");

    # The value attribute of the select element is the value of the selected option
    console.log(selectElement.value);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM