我想编写 JavaScript
代码并在 Python+Selenium
脚本中使用它。目标 URL
为 Microsoft account login page 。在这里,我想强制 onclick 打开 使用条款
页面,而不是在新选项卡中,而是在新窗口中,因此我对适当的 anchor 标记进行了一些更改。我在 JS
方面有一点经验,所以这就是我现在得到的:
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
,然后将其传递给属性:
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
中的属性看起来像
onclick="window.open('' + 引用 + '', '', 'width=800,height=600')"
。
那么如何用实际值替换引用
名称?
最佳答案
您只需根据值计算字符串:
document.querySelector('a#ftrTerms').setAttribute("onclick", "window.open('" + reference + "', '', 'width=800,height=600')")
reference
不应出现在字符串中,而应与字符串前缀和后缀的其余部分连接起来
关于javascript - 如何在 HTML 属性值中使用 JS 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41483740/