【问题标题】:How to use JS variable inside HTML attribute value如何在 HTML 属性值中使用 JS 变量
【发布时间】:2017-05-19 22:04:42
【问题描述】:

我想编写JavaScript 代码并在Python+Selenium 脚本中使用它。目标 URLMicrosoft account login page。在这里,我想强制 onclick 打开 Terms of use 页面,而不是在新选项卡中,而是在新窗口中,所以我对适当的锚标记进行了一些更改。我在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('' + reference + '', '', 'width=800,height=600')".

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

【问题讨论】:

    标签: javascript html


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2023-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多