javascript - 如何在 HTML 属性值中使用 JS 变量

标签 javascript html

我想编写 JavaScript 代码并在 Python+Selenium 脚本中使用它。目标 URLMicrosoft 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/

相关文章:

javascript - 解构时引用对象

javascript - org.springframework.web.bind.MissingServletRequestParameterException : Required Long parameter 'userId' is not present"错误

html - 如果速率降低,则显示速率 : green if the rate has increased, 红色

html - 如何阻止 Wordpress 中的可视化编辑器更改代码?

html - 跨度溢出 : hidden; doesn't show up in Firefox

html - 将 SVG 元素与页面左侧对齐

javascript - 来自父级关系的 Strongloop 属性

javascript - 在预检请求中不收到 http 403 的情况下通过 AJAX 访问 Genius API 的正确方法是什么?

javascript - 使用 jQuery 从 html 结构获取数据

javascript - 避免可拖动对象一旦掉落就变成 "droppable areas"