【问题标题】:Onclick button to switch between iframe mapsOnclick 按钮在 iframe 地图之间切换
【发布时间】:2022-01-30 13:23:19
【问题描述】:

我想通过单击 3 个不同的按钮在同一页面中显示不同的 3 个地图。 我使用了这段代码,但我不知道如何通过单击按钮在地图之间切换。我想我需要一个 javascript 函数,但我不知道该怎么做。我是网络编程新手

The 3 buttons I used

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset='utf-8'>
        <meta charset='utf-8'>
        <meta http-equiv='X-UA-Compatible' content='IE=edge'>
        <title>MAps</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel='stylesheet' type='text/css' media='screen' href='main.css'>
        <script type="text/javascript" 
        src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
      </head>
      <body>
          <div class ="navButton">
            <button class="btn bruce">Buton1 </button>
            <button class="btn info">Button2</button>
            <button class="btn warning">Buton3</button>
          </div>
          
          <iframe width="1700" height="1200" frameborder="1" scrolling="no" marginheight="0" 
              marginwidth="0" src="https://link to map1></iframe>
          <iframe width="1700" height="1200" frameborder="1" scrolling="no" marginheight="0" 
                 marginwidth="0" src="https://link to map2></iframe>
          <iframe width="1700" height="1200" frameborder="1" scrolling="no" marginheight="0" 
                 marginwidth="0" src="https://link to map3></iframe>
         </script>
        </script>
   </body>
</html>

【问题讨论】:

    标签: javascript html jquery iframe


    【解决方案1】:

    首先,注意跨域 iframe,现在进入正题。

    您可以使用变量来查看要显示的 iframe。

    let a = 0;
    

    现在,您可以使用 jQuery $(obj).hide().show() 函数在三者之间切换。

    // func() runs when button is clicked (<button onclick="func()">text</button> in the HTML)
    let a = 0;
    $(first_iframe).hide()
    $(second_iframe).hide()
    $(third_iframe).hide()
    function func() {
    if(a === 0) {
    $(first_iframe).show()
    $(second_iframe).hide()
    $(third_frame).hide()
    a++
    } else if (a === 1) {
    $(first_iframe).hide()
    $(second_iframe).show()
    $(third_frame).hide()
    a++
    } else if (a === 2) {
    $(first_iframe).hide()
    $(second_iframe).hide()
    $(third_frame).show()
    a = 0
    }
    }
    

    此方法仅使用 1 个按钮。 如果你想使用三个按钮,

    $(first_iframe).hide()
    $(second_iframe).hide()
    $(third_iframe).hide()
    
    function button1() {
    $(first_iframe).show()
    $(second_iframe).hide()
    $(third_frame).hide()
    }
    
    function button2() {
    $(first_iframe).hide()
    $(second_iframe).show()
    $(third_frame).hide()
    }
    
    function button3() {
    $(first_iframe).hide()
    $(second_iframe).hide()
    $(third_frame).show()
    }
    //add onclick events to the three buttons to their respective functions (in the html)
    

    【讨论】:

    • 非常感谢 Hermanboxcar。有用。我现在必须添加更多按钮。感谢您的帮助!
    • 将答案标记为正确可以帮助未来的用户区分正确和错误的答案。要将答案标记为正确,请单击答案左侧的复选标记。