JavaScript setAttribute 不起作用
我一直在尝试使用 setAttribute 将选择标记的名称从 oldName 更改为 newName,但是当我加载页面然后查看源代码时,oldName 仍然存在。最终,我想添加一个属性“onchange”,“function();”但我什至无法让 JS 更改标签的名称。任何帮助将不胜感激。提前致谢。我在 Mac OS X:Chrome、FF 和 Safari 上对此进行了测试。
<html>
<head>
</head>
<body>
<select name="oldName">
<option value="0">Essay 1</option>
<option value="1">Essay 2</option>
<option value="2">Essay 3</option>
</select>
<script type="text/javascript">
document.getElementsByTagName("select").item(0).setAttribute("name","newName");
</script>
</body>
</html>
I've been trying to use setAttribute to change the name of the select tag from the oldName to the newName, however when I load the page and then look at the source, the oldName remains. Ultimately, I wanted to add an attribute "onchange","function();" but I can't even get the JS to change the name of the tag. Any help would be appreciated. Thanks in advance. I tested this on Mac OS X: Chrome, FF, and Safari.
<html>
<head>
</head>
<body>
<select name="oldName">
<option value="0">Essay 1</option>
<option value="1">Essay 2</option>
<option value="2">Essay 3</option>
</select>
<script type="text/javascript">
document.getElementsByTagName("select").item(0).setAttribute("name","newName");
</script>
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的代码有效,名称发生变化。查看源代码时您不会看到名称更改。相反,请查看开发工具中生成的源代码。 (在 Chrome 中尝试
F12
)。查看源代码仅显示首次从服务器下载的源代码。使用开发工具,您可以看到页面加载后对 DOM 所做的更改。
Your code works, the name changes. You just won't see the name change when viewing source. Instead look at the generated source in a development tool. (Try
F12
in Chrome).View Source only shows the source as it is first downloaded from the server. Using a development tool you can see the changes made to the DOM after page load.
当您执行“查看源代码”时,您并不是在查看页面的 HTML,因为它存在于您面前 - 浏览器会专门获取页面的副本以向您显示源代码。这样做时,它不会解释 javascript - 因此您通过 javascript 对文档所做的任何更改都不会反映在“查看源代码”窗口中。
为了实时查看 DOM 的更改,您必须使用 Firebug 等开发工具(链接< /a>)。当然,成为 Firefox 扩展并不意味着 Internet Explorer 运气好,这就是为什么开发人员经常以 Firefox 为开发目标,并在一切合理启动和运行后担心 Internet Explorer。
IE 中有 Firebug 的替代工具(如 Firebug Lite),但没有一个工具的功能和实用性接近。
When you do "view source", you are not looking at the HTML of the page as it exists in front of you - the browser fetches a copy of the page specifically to show you the source. When doing so, it does not interpret javascript - so any changes to the document you make via javascript will not be reflected in the "view source" window.
In order to view the changes to DOM live, you will have to use a development tool like Firebug (link). Being a Firefox extension of course means no luck in Internet Explorer, which is why developers often target Firefox for development and worry about Internet Explorer after everything is reasonably up and running.
There ARE alternative tools for Firebug in IE (like Firebug Lite), but none come close to the functionality and utility.
为什么你不使用类来代替?像这样:
Why you dont use class instead? Like this: