Javascript 节点和函数使用
我有一张有四行的表,每行都有一个“id”,每个链接内都有一个文本。
我想用下一个链接innerHTML 更改单击链接的innerHTML。
因此,如果我有这个:
ONE
TWO
THREE
FOUR
例如,我单击两个,结果必须是:
ONE
THREE
TWO
FOUR
如下我的代码,它已经更改了前两个链接的顺序,但如果我单击另一个链接,它会执行相同的操作。
<html>
<head>
<script type="text/javascript">
function change()
{
var link = document.getElementsByTagName("a");
var i = 0;
var aux = link[i].innerHTML;
link[i].innerHTML = link[i+1].innerHTML;
link[i+1].innerHTML = aux;
}
</script>
</head>
<body>
<table border="1">
<tr id="1"><td><a href="#" onclick="change()">ONE</a></td></tr>
<tr id="2"><td><a href="#" onclick="change()">TWO</a></td></tr>
<tr id="3"><td><a href="#" onclick="change()">THREE</a></td></tr>
<tr id="4"><td><a href="#" onclick="change()">FOUR</a></td></tr>
</table>
</body>
</html>
我一整天都在做这件事,但我不知道还能做什么。我从 Java 和 Javascript 开始,所以数组以及 DOM 和 Javascript 函数的使用对我来说是新的。
I have a table with four rows, each one with an "id", and inside each one link with a text.
I want to change the innerHTML of the clicked link with the next one link innerHTML.
So if I have this:
ONE
TWO
THREE
FOUR
and I click on TWO for example, the result must be:
ONE
THREE
TWO
FOUR
As follows my code, which already change the order of the two first links, but it does the same if I click another link.
<html>
<head>
<script type="text/javascript">
function change()
{
var link = document.getElementsByTagName("a");
var i = 0;
var aux = link[i].innerHTML;
link[i].innerHTML = link[i+1].innerHTML;
link[i+1].innerHTML = aux;
}
</script>
</head>
<body>
<table border="1">
<tr id="1"><td><a href="#" onclick="change()">ONE</a></td></tr>
<tr id="2"><td><a href="#" onclick="change()">TWO</a></td></tr>
<tr id="3"><td><a href="#" onclick="change()">THREE</a></td></tr>
<tr id="4"><td><a href="#" onclick="change()">FOUR</a></td></tr>
</table>
</body>
</html>
I've been working on this all day and I can't see what else can I do. I'm starting with both Java and Javascript, so the use of arrays and the DOM and Javascript functions is new to me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
代码如何知道点击了哪个链接?如果你不告诉它,它就无法神奇地推断出来。
首先,删除所有这些
id
属性。它们在这里没有任何作用,只会导致混乱。接下来,传递
this
作为change
的第一个参数:onclick="change(this);"
和function change(link) {...}
。现在,重写您的
change
函数以找到要更改link
的正确链接,然后按照现在的方式进行交换。祝你好运。
How does the code know which link was clicked? If you don't tell it, it can't deduce it magically.
First off, remove all those
id
attributes. They serve no purpose here and will only lead to confusion.Next, pass
this
as the first argument ofchange
:onclick="change(this);"
andfunction change(link) {...}
.Now, rewrite your
change
function to find the right link to changelink
with, and do the swap as you are now.Good luck.
你似乎想做类似的事情:
You seem to want to do something like: