900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > html标签属性值拼接 js拼接url以及为html某标签属性赋值

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

时间:2020-01-17 05:41:41

相关推荐

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

记录

js拼接url

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

function ReturnIndex() {

var rex = RegExp("tools")

var url = window.location.origin

var new_url = "http://127.0.0.1:"+window.location.port

if (url.match(rex)) {

curr_url = window.location.origin // 获取根网址:比如:

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-"

hostname: "i-"

href: "https://i-/posts/edit"

origin: "https://i-"

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。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。