给出以下标记。
<div id="example">
<div>
<div>
<input type='hidden'></input>
</div>
</div>
</div>
如果我拥有ID为'example'的最顶部div元素的ID,我如何快速获取隐藏的输入元素?
我可以破解它,所以我可以遍历每个子元素,直到我点击输入,但是,我想改进它并利用Prototype并简单地跳转到给定div的隐藏输入。
谢谢!
答案 0 :(得分:27)
Prototype提供了很多方法来实现这一目标:
// This, from Bill's answer, is probably the fastest, since it uses the
// Browser's optimized selector engine to get straight to the element
$$('#example input[type=hidden]').first();
// This isn't bad either. You still use the browser's selector engine
// To get straight to the #example element, then you must traverse a
// (small) DOM tree.
//
// element.down(selector) selects the first node matching the selector which
// is an decendent of element
$('example').down('input');
// Here, you'll get an array containing all the inputs under 'example'. In your HTML
// there is only one.
$('example').select('input')
// You can also use element.select() to combine separate groups of elements,
// For instance, if you needed all the form elements:
$('example').select('input', 'textarea', 'select');
答案 1 :(得分:16)
$$('#example input[type=hidden]').first()
答案 2 :(得分:-2)
我更喜欢直接的方法
document.forms[0].fieldName.value
代码少,不需要使用jQuery,对代码设计更友好。