如何使用 YUI 按名称查找输入并在其后插入内容
如何使用 YUI 按名称定位文本输入并在其后插入 div?
例如,这不起作用:
<input name="some_name" type="text">
<script>
var el = new YAHOO.util.Element(document.createElement('div'));
var some_element = document.getElementsByName('some_name');
// doesn't work .... replacing 'some_element' with 'document.body' works
el.appendTo(some_element);
</script>
How can I use YUI to locate a text input by name and insert a div after it?
For example, this doesn't work:
<input name="some_name" type="text">
<script>
var el = new YAHOO.util.Element(document.createElement('div'));
var some_element = document.getElementsByName('some_name');
// doesn't work .... replacing 'some_element' with 'document.body' works
el.appendTo(some_element);
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如前所述,document.getElementsByName 返回一个数组。 您可能希望为输入提供一个与 name 属性同名的 ID。 (旁白:这对于表单来说是常见且良好的做法。当您执行此操作时,其他 js 库提供了有用的扩展。)
还要注意 insertAfter 而不是 appendTo 的使用。 您不希望 el 成为输入元素的子元素。 你希望它成为下一个兄弟姐妹。 输入没有子项。 最后,您将这些变量添加到全局命名空间中。 这可能是问题,也可能不是问题,但将代码包装在匿名函数中通常是个好主意,除非您打算让变量具有全局作用域并稍后重用它们,但随后您可能想为它们提供适当的命名空间。
希望有帮助(并且没有太多信息。);)
As mentioned, document.getElementsByName returns an array. You may want to give your input an ID with the same name as the name attribute. (Aside: This is common and good practice for forms. Other js libraries provide helpful extensions when you do this.)
Also notice the use of insertAfter rather than appendTo. You do not want el to be a child of your input element. You want it to be the next sibling. Inputs do not have children. Also lastly, you're adding these variables to the global namespace. This may or may not be a problem, but it's generally a good idea to wrap your code in an anonymous function unless you intend for the variables to have global scope and reuse them later, but then you might want to provide a proper namespace for them.
Hope that helps (and not too much info.) ;)
document.getElementsByName('some_name') 总是返回一个集合(一个数组),如果您确定该名称是唯一的,您可以安全地编写它。
document.getElementsByName('some_name') always return a collection (an Array), if you are sure that the name is unique you can safely write this.
使用 YUI 3,您现在可以执行此操作:
但请记住YUI 即将停产!
With YUI 3 you can now do this:
But keep in mind YUI is being discontinued!
您基本上会设置一个条件并说 name="some_name"。
请参阅下面的代码并观察是否仍然插入了
段落。
You basically put a condition and say name="some_name".
See the code below and observe that is still does insert the
aragraph.