【问题标题】:javascript link isn't working on click; function works when page loadsjavascript 链接在点击时不起作用;页面加载时功能起作用
【发布时间】:2015-04-07 16:51:43
【问题描述】:
var randomNumber

// generate the random numbers based on the length of the image array
randomNumber = Math.floor(Math.random() * topImages.length);

function shuffleTop(){
  document.getElementById("topImage").src = topImages[randomNumber];
};

$("p a#shuffle").click(shuffleTop());

这是我源代码中的链接:

<p><a href="#" id="shuffle">SHUFFLE</a></p>

【问题讨论】:

    标签: javascript function random shuffle


    【解决方案1】:

    您正在运行该函数,它返回的内容正在分配给客户端。您没有分配对函数 shuffleTop 的引用。

    $("p a#shuffle").click(shuffleTop());
    

    需要

    $("p a#shuffle").click(shuffleTop);
    

    你只生成一次数字,将随机数生成器移到里面。

    function shuffleTop(){
      randomNumber = Math.floor(Math.random() * topImages.length);
      document.getElementById("topImage").src = topImages[randomNumber];
    };
    

    【讨论】:

    • 多伊,谢谢!现在下一个问题是它只运行一次,然后我必须重新加载页面才能让它再次工作。
    • 澄清一下:您分配给点击事件的是 shuffleTop 返回的内容(例如,什么都没有),而不是 shuffleTop 本身。
    • 因为随机数在外面。
    • 天哪,非常感谢你,我已经坚持了 3 个小时。
    【解决方案2】:

    你需要给你的点击事件一个函数回调:

    $("p a#shuffle").click(shuffleTop);
    

    【讨论】:

      【解决方案3】:

      如果你使用jQuery,不妨使用jQuery来设置图片src。

      $("#topImage").attr("src",topImages[randomNumber]);
      

      我假设 topImages[randomNumber] 已经包含了一个图片的 URLrelative 到 HTML 页面。

      【讨论】:

        【解决方案4】:

        首先,如果你有 jQuery,为什么还要使用纯 js?

        randomNumber = Math.floor(Math.random() * topImages.length);
        function shuffleTop(){
          $("#topImage").attr('src', topImages[randomNumber]);
        };
        $("p a#shuffle").on('click', shuffleTop); // i re-write this to call function.
        

        必须努力

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多