如何在 HTML 属性值中使用 JS 变量 [英] How to use JS variable inside HTML attribute value

查看:133
本文介绍了如何在 HTML 属性值中使用 JS 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写 JavaScript 代码并在 Python+Selenium 脚本中使用它.目标 URLMicrosoft 帐户登录页面.在这里,我想强制 onclick 打开 Terms of use 页面,而不是在新选项卡中,而是在新窗口中,因此我对适当的锚标记进行了一些更改.我对 JS 有一点经验,所以这是我现在得到的:

I want to write JavaScript code and to use it in Python+Selenium script. Target URL is Microsoft account login page. Here I want to force onclick opening Terms of use page not in new tab, but in new window so I made some changes to appropriate anchor tag. I have a little experience in JS, so this is what I got for now:

document.querySelector('a#ftrTerms').setAttribute("onclick", "window.open('https://login.live.com/gls.srf?urlID=WinLiveTermsOfUse&mkt=EN-US&vv=1600', '', 'width=800,height=600')")
document.querySelector('a#ftrTerms').removeAttribute('href')

...这很好用(不是最好的方法,但没关系).但是,重定向 URL 是硬编码的,因此我使用以下方法首先从 href 获取 URL,然后将其传递给属性:

...and this works fine (not the best way, but it's ok). However, redirection URL is hardcoded, so I use following to get URL from href first and then pass it to attribute:

var reference = document.querySelector('a#ftrTerms').getAttribute('href');
document.querySelector('a#ftrTerms').setAttribute("onclick", "window.open(\'' + reference +  '\', '', 'width=800,height=600')")
document.querySelector('a#ftrTerms').removeAttribute('href')

...并且此代码不起作用:我在 HTML 中的属性看起来像

...and this code is not working: my attribute in HTML appears like

onclick="window.open('' + 参考 + '', '', 'width=800,height=600')".

那么如何将reference名称替换为其实际值?

So how to substitute reference name with its actual value?

推荐答案

您只需要根据值计算字符串:

You simply need to calculate the string from the value:

document.querySelector('a#ftrTerms').setAttribute("onclick", "window.open('" + reference + "', '', 'width=800,height=600')")

reference 不应在字符串中,而应与字符串的其余前缀和后缀连接

reference should not be in the string, but concatenated with the rest of the string prefix and suffix

这篇关于如何在 HTML 属性值中使用 JS 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆