【问题标题】:PrototypeJS input value in each() enumeration在 each() 枚举中的 PrototypeJS 输入值
【发布时间】:2014-07-22 08:35:10
【问题描述】:

为什么在未选中复选框时,下面的 HTML/JS 会返回“on”值?此代码(目前)在 tab.my 上有效。

HTML

<button type="button" id="init" class="btn btn-primary btn-sm">Init</button>

<form id="domains">

  <div id="domain1">
    <input type="checkbox" name="input1" />
    <a>Domain 1</a>
  </div>

  <div id="domain2">
    <input type="checkbox" name="input2" />
    <a>Domain 2</a>
  </div>

</form>

JS

$('init').observe('click', init);

function init() {
  $('domains').select('div').each(function(domain){
    console.log(domain.select('input')[0].value);
  });
}

我阅读了this 的帖子,但我正在尝试学习有关 JavaScript 性能的最佳实践,并获得更多基础知识。我的猜测是,您在 select() 方法中使用 $ 实用程序的次数越多,使用 $$ 实用程序的次数越少,它所循环的次数就越少。下面的函数返回了正确的值,但我需要访问每个“域 div”中的其他元素。

function init() {
  $('domains').getElements().each(function(input){
    console.log($F(input));
  });
}

我想也许我应该使用 $F 实用程序,但是下面的函数返回了 JS 错误

未捕获的类型错误:无法读取未定义的属性“toLowerCase”

function init() {
  $('domains').select('div').each(function(domain){
    console.log($F(domain.select('input')));
  });
}

【问题讨论】:

    标签: javascript html performance prototypejs


    【解决方案1】:

    $F() 方法要求元素要么有 ID,要么已经被 Prototype 找到并扩展。这是这个构造的一个有用的快捷方式:$(id or reference).getValue();

    要在这里做你想做的事,你可以使用“双倍美元”方法,但如果你以一个 id 开头,它将与“通过 ID 查找,查找孩子”一样快" $(id).select() 的方法。

    $$('#domains div input').each(function(elm){
      console.log($F(elm));
    });
    

    第二次尝试失败的原因是因为您使用了 select('input'),它总是返回一个数组作为结果。如果你使用 down('input'),那将返回输入本身,这将与 $F() 一起使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-02
      • 2020-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多