javascript - 在内联事件处理程序中引用 `this`

标签 javascript html

我希望能够在 JavaScript 'mouseover' 中传递 'this'。我基本上想从链接(唯一的)获取 href 并将其传递给每个下载按钮。但我收到错误消息:

undefined is not an object (evaluating 'this.getElementsByClassName('downLoad_link')[0].href = x)

我对此很陌生,所以我希望有人能帮助我! :)

这是我的代码:

<a onmouseover="this.getElementsByClassName('downLoad_link')[0].href = 'www.example.com'" href="" class="downLoad_link" download>
    <button class="download">Download</button>
</a>

编辑:

当我解决此问题时,

'www.example.com' 将被变量替换!

好的,我的新代码是这样的:

Javascript:

    <script type="text/javascript" language="javascript">
       var x = this.getElementsByClassName('getDownloadLink')[0].href; //this is not working!
    </script>

HTML:

<a onmouseover="this.getElementsByClassName('downLoad_link')[0].href = x" href="" class="downLoad_link" download>Download</a>

最佳答案

只使用this而不是this.getElementsByClassName('downLoad_link')[0]

<a onmouseover="this.href = 'www.example.com'" href="" class="downLoad_link" download>
  <button class="download">
    Download
    </button>
</a>

关于javascript - 在内联事件处理程序中引用 `this`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49829706/

相关文章:

javascript - 在 Bootstrap 模式中自定义 Google 搜索,在相同模式中打开结果

javascript - Mongoose - RangeError : Maximum Call Stack Size Exceeded

javascript - 防止Ajax网站按下后退按钮后跳回顶部

objective-c - 将 HTML 文件添加到 SQLite 数据库

javascript - 在 google script/Sheet 中组合 3 个独立的 Onedit 函数

javascript - 网页 javascript 根本不执行

javascript - 您将如何使用这两种概念上不同的方法来编写 javaScript 对象

html - 为什么父div与 child 的高度不一样?

jquery - 自动完成设计

javascript - 如何调整 SVG 的大小?