当前位置:首页 > Web开发 > 正文

js拼接url以及为html某标签属性赋值

2024-03-31 Web开发

标签:

记录 js拼接url

比如有些时候我们需要为某按钮实现跳转,可以利用下面的方式做到:

function ReturnIndex() { var rex = RegExp("tools") var url = window.location.origin var new_url = ":"+window.location.port if (url.match(rex)) { curr_url = window.location.origin // 获取根网址:比如:https://www.baidu.com a = curr_url.split(".")[0] now = a.split("//")[1] window.location.href = curr_url.replace(now, "www") } else { console.log(new_url) window.location.href = new_url } }; $("#ReturnBtn").on('click', function () { ReturnIndex() });

说明:

获取URL全部信息:window.location

拥有的方法和属性,我这里以博客园为例,按F12,在console下调试:

ancestorOrigins: DOMStringList {length: 0} assign: ? assign() hash: "" host: "i-beta.cnblogs.com" hostname: "i-beta.cnblogs.com" href: "https://i-beta.cnblogs.com/posts/edit" origin: "https://i-beta.cnblogs.com" pathname: "/posts/edit" port: "" protocol: "https:" reload: ? reload() replace: ? () search: "" toString: ? toString() valueOf: ? valueOf() Symbol(Symbol.toPrimitive): undefined __proto__: Location

从上面看到,这里我使用的主要是origin、port、href这仨属性,分别对应请求源、端口、超链接URL。

url拼接,因为我这里是从二级域名往一级域名跳转,所以使用了字符串的替换:

先定义包含tools的正则:var rex = RegExp("tools")

然后做了一个判断语句【这里是因为方便本地和远程服务调试使用】,,如果当前url包含二级域名tools,则替换为一级域名www,然后按钮跳转回一级域名资源下;若无,则代表是本地环境,跳转到ip+port页面下。

给指定标签属性赋值

使用选择器+attr方法来赋值。attr(attributeName: string, value: string | number)

$(".qrcode_modal").attr('src', new_url) // 给src赋值

如上则是给class为qrcode_modal的标签src属性赋值new_url。

js拼接url以及为html某标签属性赋值

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/42282.html