选择标签、替换值 (JavaScript)
在今天之前我从未使用过 JavaScript,所以我一边学习一边学习。
在网页上,我想选择所有带有“exampleClass”类的 html 输入标签,并且我想替换该值。谁能向我展示一个关于如何执行此操作的良好/快速的代码片段,或者为我指明另一个线程或教程的正确方向?
谢谢你!
Before today I have never before used JavaScript so I'm trying to learn as I go here.
On a webpage I want to select all html input tags with the class "exampleClass" and I want to replace the value. Can anyone show me a good/quick code snippet on how to do this or point me in the right direction to another thread or tutorial?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您使用 jQuery,
或者不需要 IE7 支持 querySelectAll
或使用 getElementsBytagName:
This is trivial if you use jQuery:
or if no IE7 support is required querySelectAll
or filter all input tags with getElementsBytagName:
如果您想更好地了解其工作原理,请务必检查 这个答案。
If you want a better hint of how it works, be sure to check this answer.
纯 Javascript
在纯 javascript(没有类似 jQuery 的框架)中,您可以这样做:
但是,旧版本的 IE 不支持
getElementsByClassName()
(直到 IE9)。如果您想让纯 JS 版本适用于较旧的浏览器,那么您必须获得getElementsByClassName()
的替代品,以便在不支持它时使用。您可以通过 Google 找到许多实现。这是其中之一: http://robertnyman.com/2008 /05/27/the-ultimate-getelementsbyclassname-anno-2008/。像 jQuery 这样的jQuery
框架对于这种操作非常非常有用,并且它们具有更好的跨浏览器和旧浏览器支持。在 jQuery 中,这个操作几乎在任何地方都可以工作,而且只是这一行。
Sizzle
如果您想要良好的跨浏览器支持,但想要比 jQuery 更轻量级的东西,您可以只使用 Sizzle 选择器库(这是 jQuery 内部使用的),在这种情况下,代码将是这样的:
Plain Javascript
In plain javascript (no jQuery-like framework), you could do it like this:
But,
getElementsByClassName()
isn't supported in older versions of IE (not until IE9). If you want to make the plain JS version work with older browsers, then you have to get a substitute forgetElementsByClassName()
for use when it isn't supported. There are many implementations which you can find with Google. Here's one of them: http://robertnyman.com/2008/05/27/the-ultimate-getelementsbyclassname-anno-2008/.jQuery
Frameworks like jQuery are very, very useful for this kind of operation and they have better cross-browser and old-browser support. In jQuery, this operation would work pretty much everywhere and be just this one line.
Sizzle
If you want good cross-browser support, but want something lighter weight than jQuery, you can use just the Sizzle selector library (which is what is used inside of jQuery) in which case the code would be this:
小提琴演示:http://jsfiddle.net/maniator/4aWje/
Fiddle Demo: http://jsfiddle.net/maniator/4aWje/
好吧,既然你是 JavaScript 新手,那么 jQuery 会很容易上手,因为它有非常强大的选择器 与普通 JavaScript 相比相对容易编写。 jQuery 示例如下所示:
试试这个:
Well, since you are new to JavaScript then jQuery would be an easy to start because it has very powerful selectors that are relatively easy to write vs. plain JavaScript. A jQuery example would look like this:
Try this: