Javascript交换三段

时间:2016-11-18 13:57:22

标签: javascript html dom

您好我的交换功能无法正常工作我错过了什么我似乎无法找到问题,请参阅下文。提前谢谢!

<html>
 <head>
    <title>Three Pharagraphs</title>
 <script>
    function swap(a,b) {
        var c = a.innerHTML;
        a.innerHTML = b.innerHTML;
        b.innerHTML = c;
    }
    window.onload = function() {
        var link1 = document.getElementById('link1.1');
        var link2 = document.getElementById('link2.2');
        var link3 = document.getElementById('link3.3');
        var p1 = document.getElementById('line1');
        var p2 = document.getElementById('line2');
        var p3 = document.getElementById('line3');
        link1.onclick = swap(p1,p3);
        link2.onclick = swap(p2,p3);
        link3.onclick = swap(p1,p3);
    }
 </script>
 </head>
 <body>
    <p id="line1">What is Lorem Ipsum?</p>
    <p id="line2">Why do we use it?</p>
    <p id="line3">The standard Lorem Ipsum passage.</p>
    <p><a href="#" id="link1.1">1<->2</a> <a href="#" id="link2.2">2<->3</a><a href="#" id="link3.3">3<->1</a>
 </body>
</html>

2 个答案:

答案 0 :(得分:1)

更改link1,2和3 onclick功能,如:

        link1.onclick = function() {
          swap(p1,p3);
        }
        link2.onclick = function() {
          swap(p2,p3);
        }
        link3.onclick = function() {
          swap(p1,p3);
        }

答案 1 :(得分:1)

您正在调用该函数并设置它返回到onclick的内容。你正在做的基本上是link1.onclick = undefined;,因为该方法不会返回任何内容。

link1.onclick = function() { swap(p1,p3); }