【问题标题】:Confusion with Javascript variable scoping与 Javascript 变量作用域混淆
【发布时间】:2018-05-23 19:28:17
【问题描述】:

我正在尝试在 JS 中创建一个简单的测试。我有一个创建 4 个单选按钮并将它们添加到 html 的函数。当我调用它n 次时,我只需将相同的 4 个单选按钮添加到 div 并且当我尝试从第 4 个问题中选择一个答案时,它仍然会从第一个 div/问题中选择答案。

function getRandom(min, max) {
    return Math.random() * (max - min) + min;
}

function test_2() {

  var a = getRandom(0, 10) - 5;

  while (a == 0)
    a = getRandom(0, 10) - 5;

  var b = getRandom(0, 10) - 5;

  //create the div in which i add the radio buttons
  var div = document.createElement('div');
  div.setAttribute('class', 'parent');
  div.setAttribute('id', '2');

  document.body.appendChild(div);

  //create the radio button and set its attributes
  var radio1 = document.createElement('input');
  var label1 = document.createElement('label');
  label1.innerHTML = a * 4 + b;
  label1.setAttribute('for', 'radio1');
  radio1.setAttribute('type', 'radio');
  radio1.setAttribute('value', a * 4 + b);
  radio1.setAttribute('id', 'radio1');
  radio1.setAttribute('name', 'answ');
  radio1.innerHTML = a * 4 + b;

  //add it to the div
  div.appendChild(radio1);
  div.appendChild(label1);
}

test_2();

【问题讨论】:

  • 请简化代码示例,仅包含问题的相关部分。
  • 所有divinput[type=radio] 元素都被赋予相同的id 值。 ids 在文档中必须是唯一的。
  • @YotamSalmon 代码不需要简化。这里没有什么过分的。相反,应该添加更多相关代码,以便我们可以重新创建场景。
  • 没有足够的代码可以确定,但我怀疑问题在于id 属性在必须唯一时共享值。
  • 是的,我认为 id 是问题。谢谢大家

标签: javascript html scope


【解决方案1】:

每个问题的名称属性必须不同:

    <form>
    <!-- Question 01 -->
    <fieldset id="group1">
        <input type="radio" value="" name="group1">
        <input type="radio" value="" name="group1">
    </fieldset>

    <fieldset id="group2">
    <!-- Question 02 -->
        <input type="radio" value="" name="group2">
        <input type="radio" value="" name="group2">
        <input type="radio" value="" name="group2">
    </fieldset>
</form>

【讨论】:

    【解决方案2】:

    这可能是因为每个“单选按钮包”test_2() 正在生成具有相同的 name 属性值 (answ)。 一个快速的解决方案是将name 作为参数发送到test2,这样您就可以像这样“命名空间”您的单选按钮:

    function test_2(name) {
    
      var a = getRandom(0, 10) - 5;
    
      ...
    
      radio1.setAttribute('name', name + '-answ');
    
      ...
    

    }

    这样,如果你在循环中调用这个函数,你可以传入索引作为名称参数,并确保名称的唯一性。

    【讨论】:

      猜你喜欢
      • 2012-03-17
      • 2014-08-15
      • 1970-01-01
      • 1970-01-01
      • 2017-02-17
      • 1970-01-01
      • 2014-06-13
      • 1970-01-01
      • 2016-01-14
      相关资源
      最近更新 更多