我有一个网络应用程序,它使用协议(protocol)相关的 URL 来使所有内容尽可能动态,问题是在某些情况下这些不起作用,例如作为第 3 方身份验证的重定向 URL,所以问题是存在一些我可以通过这种方式指向 HTML 代码中引用为 data-redirect-url="//abc.com/auth.php"
的重定向 URL。 HTML 中的属性 <button>
并根据事件协议(protocol)在其前面添加 http/https?
顺便说一句,我知道最好仅通过 HTTPS 提供内容,而且人们可能不想再使用这些 URL,但我希望是动态的,因为例如使用本地主机测试 HTTPS 确实不需要。
<小时/>长话短说。 如果是 HTTP
替换
(php-正则表达式)data-redirect-url="//(.+?)"
与
(php-正则表达式)data-redirect-url="http://$1"
如果是 HTTPS,
改为使用
(php-正则表达式)data-redirect-url="https://$1"
我对 js 很不擅长(事实上,我会尽量避免使用它),所以尽量让代码易于理解,并且尽可能不要太复杂。
最佳答案
您可以使用 location.protocol
返回当前 URL 的协议(protocol)。 http:
或 https:
根据您的评论,您有一个按钮:
<button class="btn btn-block btn-lg btn-info" data-redirect-url="//somedynamicallygeneratedurl">
要更改data-redirect-url
,请使用:
var urlButtons = document.querySelectorAll('.btn[data-redirect-url]');
for(var _index = 0; _index < urlButtons.length; _index++) {
var btn = urlButtons[_index];
btn.setAttribute('data-redirect-url', location.protocol+btn.getAttribute('data-redirect-url'));
console.log(btn.getAttribute('data-redirect-url'));
}
关于javascript - 通过 HTML 代码中的搜索和替换填写协议(protocol)相关 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34897149/