【问题标题】:Trying to add a javascript function to a button尝试将 javascript 函数添加到按钮
【发布时间】:2017-03-12 22:23:37
【问题描述】:

我对 HTML 比较陌生,所以请多多包涵。我正在尝试添加一个已经提供给我的简单 javascript 函数,该函数将图像从 Flickr 抓取到一个按钮。当我单击按钮时,什么也没有发生。我不确定错误发生在哪里,但我认为它与函数未正确执行有关。

HTML:

   <!DOCTYPE html>
    <html>
    <head>
        <title>getJSON</title>
        <meta charset="utf-8" />
        <script src="jquery-3.1.1.min.js"></script>
    </head>
    <body>
    <button onclick="myFunction()">Click me</button>
    <script>
    function myFunction() 
    {  //Functions don't need names. This function will simply run when the page loads
      var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
      $.getJSON( flickerAPI, 
      {  // The "$" simply refers to jQuery. This calls the getJSON function that is found inside jquery-3.1.1.min.js
        tags: "Baruch College", //Some filter information in the format set by Flickr, who owns the JSON
        tagmode: "any",
        format: "json"
      })
        .done(function( data ) 
        { //Here, a an unnamed function is created made into the event handler for the "done" event... in other words, this is the code that will manifest itself when the getJSON is done.
          $.each( data.items, function( i, item ) 
          {
            $( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );
            if ( i === 5 ) 
            {
              return false;
            }
          });
        });
    }
    </script>

    </body>
</html>

我上传了HTML中提到的jquery脚本:http://pastebin.com/2CfRNkvq

【问题讨论】:

  • 您必须在本地服务器上运行您的页面。
  • 当前运行的服务器是什么?

标签: javascript jquery function button


【解决方案1】:

您需要指定检索图像后的放置位置。在 JavaScript 代码中,您可以看到它为每个图像创建了一个 &lt;img&gt; 标记并将其附加到带有 id="images" 的元素。

只需将id="images" 添加到按钮元素,如下所示:

&lt;button onclick="myFunction()" id="images"&gt;Click me&lt;/button&gt;

当您单击按钮时,图像将被放置在按钮内。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-18
    • 2012-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 2018-07-01
    • 1970-01-01
    相关资源
    最近更新 更多