【问题标题】:How to prepend a https to url on click - jquery如何在点击时将 https 添加到 url - jquery
【发布时间】:2014-04-23 17:07:17
【问题描述】:

我遇到了一种情况,当用户单击按钮时,我必须启用 https。

我目前的网址如下:myurl.com

我必须做到以下几点:

$(".btn").click(function(){

// change url to https://myurl.com

});

我当前按钮的html:

<button class="btn" data-statsopt_noninteraction="" data-statsopt_value="" data-statsopt_label="login" data-statsaction="account-actions" data-statscategory="header-events">LOG IN</button>

任何帮助将不胜感激

谢谢

【问题讨论】:

  • 你的意思是你想在这里做一个重定向?还是您的按钮真的是提交输入元素,您想更改表单目标?
  • 我不想要任何重定向..我的问题只有在执行 onclick 时当前 url 是 https 时才能解决
  • 我不想要任何重定向....然后您可以在服务器端进行一些调整。
  • 对,我倾向于将按钮换成链接 - 导致浏览器转到新页面是链接的目的!

标签: javascript jquery


【解决方案1】:

您可以使用replace()将当前协议http://替换为https://

$(".mybutton").click(function(){
    location.href = location.href.replace("http://", "https://");
});

或更好地检查您当前的 URL 是否为 https://,然后重定向页面:

$(".mybutton").click(function(){
    if (location.href.indexOf("https://") == -1) {
        location.href = location.href.replace("http://", "https://");
    }
});    

【讨论】:

  • 这导致重定向..我不想要:(
  • URL 重定向是一种 Web 服务器功能,可将用户从一个 URL 发送到另一个 URL,这是您在问题中的要求。
【解决方案2】:
$(".mybutton").click(function(){
        window.location.href = "https://myurl.com";
});

【讨论】:

    【解决方案3】:

    仅将仅 JS 操作附加到可编写脚本的元素(在本例中为按钮)是可访问性的禁忌。通过这样做,您实际上可以防止使用非支持用户代理的人访问您的内容。你应该添加一个noscript 元素:

    <button id="js-http-action">HTTPS</button>
    <noscript>
       <a href="https://yoururl/">HTTPS</a>
    </noscript>
    

    在 Lynx 等文本浏览器中,这将受到用户的极大欢迎。 :-)

    【讨论】:

      【解决方案4】:
      $(".mybutton").click(function(){
      
      // change url to https://myurl.com
      window.location.href='https://myurl.com';
      
      });
      

      【讨论】:

      • 请详细说明答案。
      【解决方案5】:
      $(".mybutton").click(function(){    
        var str = document.URL     
        location.href = str.replace('http','https');
      });
      

      【讨论】:

        【解决方案6】:

        你可以这样做:

        $(".btn").click(function(){
            var url = window.location.href.replace(/http/, 'https');
            window.location.href = url;
        });
        

        【讨论】:

        • 我会将协议正则表达式锚定到字符串的开头,否则可能会产生一些意想不到的副作用;-)
        【解决方案7】:
        $(".mybutton").click(function () {
            url = "www.myurl.com";
            url = 'http://' + url;
        });
        

        【讨论】:

        • 不要忘记格式化您的代码 - 在 UI 中有一个按钮。 就个人而言我倾向于认为,回答一个已经有五个几乎相同答案的问题没有任何价值,除非你的贡献增加了一些新的东西。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-09
        • 2012-04-03
        • 1970-01-01
        • 1970-01-01
        • 2012-01-28
        • 2015-05-22
        相关资源
        最近更新 更多